在您的代码中,文件在第一行被消耗(耗尽),因此下一行不会返回任何计数:第一个 file.read() 读取文件的全部内容并将其作为字符串返回。第二个file.read() 没有什么要读取的,只返回一个空字符串'' - 第三个file.read() 也是如此。
这是一个应该做你想做的版本:
from collections import Counter
counter = Counter()
with open('my_output', 'r') as file:
for line in file:
counter.update(line.split())
print(counter)
你可能需要做一些预处理(为了摆脱特殊字符和,和.等等)。
Counter 在 python 标准库中,对于这类事情非常有用。
请注意,这种方式您只需对文件进行一次迭代,而不必随时将整个文件存储在内存中。
如果您只想跟踪某些单词,您可以只选择它们而不是将整行传递给计数器:
from collections import Counter
import string
counter = Counter()
words = ('wordA', 'wordB', 'wordC')
chars_to_remove = str.maketrans('', '', string.punctuation)
with open('my_output', 'r') as file:
for line in file:
line = line.translate(chars_to_remove)
w = (word for word in line.split() if word in words)
counter.update(w)
print(counter)
我还提供了一个预处理示例:punctuation 将在计数之前被删除。