我有一个由许多字符串组成的文件。看起来像
sdfsdf sdfsdf测试gggg uff测试fffffffff sdgsdgsdgsdg uuuttt 555555555 ddfdfdfff dddd4444 66677565 sdfsdf5 556e4ergferg ergdgdfgtest测试
如何计算所有单词“测试”。我试过了,但我只有这个结果
f = open("file")
words = 0
for s in f:
i = s.find('test')
if i > -1:
words += 1
print(words)
f.close()
这个脚本只计算包含单词"test“的字符串。怎么数单词?
发布于 2016-02-24 19:01:08
如果您想找到所有匹配的:
with open("file") as f:
numtest = f.read().count("test")
如果只想找到单词匹配:
with open("file") as f:
numtest = f.read().split().count("test")
发布于 2016-02-24 19:03:04
单线:
s.split().count('test')
发布于 2016-02-24 19:00:42
这应该能行。
from collections import Counter
with open('myfile.txt', 'r') as f:
words = f.read().split()
counts = Counter(words)
print counts["test"] #counts just of exact string "test"
#find all strings containing test (e.g 'atest', 'mytest')
print sum([val for key,val in counts.iteritems() if "test" in key])
https://stackoverflow.com/questions/35610676
复制相似问题