首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何计算Python文件中的单词"test“?

如何计算Python文件中的单词"test“?
EN

Stack Overflow用户
提问于 2016-02-24 18:57:06
回答 5查看 331关注 0票数 0

我有一个由许多字符串组成的文件。看起来像

sdfsdf sdfsdf测试gggg uff测试fffffffff sdgsdgsdgsdg uuuttt 555555555 ddfdfdfff dddd4444 66677565 sdfsdf5 556e4ergferg ergdgdfgtest测试

如何计算所有单词“测试”。我试过了,但我只有这个结果

代码语言:javascript
运行
复制
f = open("file")
words =  0
for s in f:
    i = s.find('test')
    if i > -1:
        words += 1
print(words)
f.close()

这个脚本只计算包含单词"test“的字符串。怎么数单词?

EN

回答 5

Stack Overflow用户

发布于 2016-02-24 19:01:08

如果您想找到所有匹配的:

代码语言:javascript
运行
复制
with open("file") as f:
    numtest = f.read().count("test")

如果只想找到单词匹配:

代码语言:javascript
运行
复制
with open("file") as f:
    numtest = f.read().split().count("test")
票数 1
EN

Stack Overflow用户

发布于 2016-02-24 19:03:04

单线:

s.split().count('test')

票数 1
EN

Stack Overflow用户

发布于 2016-02-24 19:00:42

这应该能行。

代码语言:javascript
运行
复制
   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])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35610676

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档