这篇文章主要介绍python如何统计字符串每个单词出现的次数,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
统计字符串每个单词出现的次数。
def word_amount(sentence):
split_list = sentence.split()
dict_result = {}
for word_name in split_list:
if word_name not in dict_result.keys():
dict_result[word_name] = 1
else:
dict_result[word_name] += 1
return dict_result
if __name__ == '__main__':
sentence = "I can because i think i can"
dict_result = word_amount(sentence)
print(dict_result)
或者:
if __name__ == '__main__':
sentence = "I can because i think i can"
result = {word: sentence.split().count(word) for word in set(sentence.split())}
print(result)
或者:
from collections import Counter
if __name__ == '__main__':
sentence = "I can because i think i can"
counts = Counter(sentence.split())
print(counts)
以上是“python如何统计字符串每个单词出现的次数”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。