如何计算 Python 中的一个特定单词?

新手上路,请多包涵

我想计算文件中的特定单词。

例如,“apple”在文件中出现了多少次。我试过这个:

 #!/usr/bin/env python
import re

logfile = open("log_file", "r")

wordcount={}
for word in logfile.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
for k,v in wordcount.items():
    print k, v

通过用“apple”替换“word”,但它仍然会计算我文件中所有可能的单词。

任何建议将不胜感激。 :)

原文由 pluvki 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 407
2 个回答

你可以只使用 str.count() 因为你只关心单个单词的出现:

 with open("log_file") as f:
    contents = f.read()
    count = contents.count("apple")

但是,为了避免一些极端情况,例如错误地计算像 "applejack" 这样的单词,我建议您使用 正则表达式

 import re

with open("log_file") as f:
    contents = f.read()
    count = sum(1 for match in re.finditer(r"\bapple\b", contents))

\b 在正则表达式中确保模式开始和结束于 _单词边界_(而不是较长字符串中的子字符串)。

原文由 Eugene Yarmash 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您只关心一个词,那么您不需要创建字典来跟踪每个词的计数。您可以逐行遍历文件并找到您感兴趣的单词的出现。

 #!/usr/bin/env python

logfile = open("log_file", "r")

wordcount=0
my_word="apple"
for line in logfile:
    if my_word in line.split():
        wordcount += 1

print my_word, wordcount

但是,如果您还想计算所有单词的数量,并且只打印您感兴趣的单词的单词计数,那么对您的代码进行这些小的更改应该会起作用:

 #!/usr/bin/env python
import re

logfile = open("log_file", "r")

wordcount={}
for word in logfile.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
# print only the count for my_word instead of iterating over entire dictionary
my_word="apple"
print my_word, wordcount[my_word]

原文由 Wajahat 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏