首页 > 编程语言 > 详细

python 统计字符串每个单词出现的次数

时间:2019-09-18 19:03:33      阅读:426      评论:0      收藏:0      [点我收藏+]

方法一:

sentence = "I can because i think i can"
result = {word: sentence.split().count(word) for word in set(sentence.split())}
print(result)

方法二:

def count(str):
    count_words = str.split()
    count_word = {}
    for word in count_words:
        if word not in count_word.keys():
            count_word[word] = 1
        else:
            count_word[word] += 1
    return count_word

print(count(I can because i think i can))

方法三:

from collections import Counter

str = I can because i think i can
counts = Counter(str.split())
print(counts)

 

python 统计字符串每个单词出现的次数

原文:https://www.cnblogs.com/a595452248/p/11544481.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!