我有一个字符串" Hello I am going to I with hello am".我想找出一个单词在字符串中出现的次数.示例hello发生2次.我试过这种方法只打印字符 -
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")
Run Code Online (Sandbox Code Playgroud)
我想学习如何找到字数.
Joe*_*ett 36
如果要查找单个单词的计数,只需使用count:
input_string.count("Hello")
Run Code Online (Sandbox Code Playgroud)
使用collections.Counter和split()计算所有单词:
from collections import Counter
words = input_string.split()
wordCount = Counter(words)
Run Code Online (Sandbox Code Playgroud)
Counter来自收藏品是你的朋友:
>>> from collections import Counter
>>> counts = Counter(sentence.lower().split())
Run Code Online (Sandbox Code Playgroud)
from collections import *
import re
Counter(re.findall(r"[\w']+", text.lower()))
Run Code Online (Sandbox Code Playgroud)
usingre.findall比 更通用split,因为否则您将无法考虑诸如“不要”和“我会”等缩写。
演示(使用您的示例):
>>> countWords("Hello I am going to I with hello am")
Counter({'i': 2, 'am': 2, 'hello': 2, 'to': 1, 'going': 1, 'with': 1})
Run Code Online (Sandbox Code Playgroud)
如果您希望进行许多这样的查询,这将只执行一次 O(N) 工作,而不是 O(N*#queries) 工作。
| 归档时间: |
|
| 查看次数: |
40726 次 |
| 最近记录: |