如何查找字符串中单词的计数? [英] How to find the count of a word in a string?
本文介绍了如何查找字符串中单词的计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串Hello I am going to I with hello am
".我想找出一个单词在字符串中出现的次数.示例 hello 出现 2 次.我尝试了这种只打印字符的方法 -
I have a string "Hello I am going to I with hello am
". I want to find how many times a word occur in the string. Example hello occurs 2 time. I tried this approach that only prints characters -
def countWord(input_string):
d = {}
for word in input_string:
try:
d[word] += 1
except:
d[word] = 1
for k in d.keys():
print "%s: %d" % (k, d[k])
print countWord("Hello I am going to I with Hello am")
我想学习如何计算字数.
I want to learn how to find the word count.
推荐答案
如果要查找单个单词的计数,只需使用count
:
If you want to find the count of an individual word, just use count
:
input_string.count("Hello")
使用 collections.Counter
和 split()
来统计所有的单词:
Use collections.Counter
and split()
to tally up all the words:
from collections import Counter
words = input_string.split()
wordCount = Counter(words)
这篇关于如何查找字符串中单词的计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文