gpt4 book ai didi

python - 使用count方法统计文本文件中的某个单词

转载 作者:太空宇宙 更新时间:2023-11-04 08:47:44 25 4
gpt4 key购买 nike

我正在尝试计算单词“the”在保存为文本文件的两本书中出现的次数。我正在运行的代码为每本书返回零。

这是我的代码:

def word_count(filename):
"""Count specified words in a text"""
try:
with open(filename) as f_obj:
contents = f_obj.readlines()
for line in contents:
word_count = line.lower().count('the')
print (word_count)

except FileNotFoundError:
msg = "Sorry, the file you entered, " + filename + ", could not be found."
print (msg)

dracula = 'C:\\Users\\HP\\Desktop\\Programming\\Python\\Python Crash Course\\TEXT files\\dracula.txt'
siddhartha = 'C:\\Users\\HP\\Desktop\\Programming\\Python\\Python Crash Course\\TEXT files\\siddhartha.txt'

word_count(dracula)
word_count(siddhartha)

我做错了什么?

最佳答案

您正在为每次迭代重新分配 word_count。这意味着最后它将与文件最后一行中 the 的出现次数相同。你应该得到总和。另一件事:there 应该匹配吗?可能不会。您可能想使用 line.split()。此外,您可以直接遍历文件对象;不需要 .readlines()。最后,使用生成器表达式来简化。我的第一个例子没有生成器表达式;第二个是:

def word_count(filename):
with open(filename) as f_obj:
total = 0
for line in f_obj:
total += line.lower().split().count('the')
print(total)
def word_count(filename):
with open(filename) as f_obj:
total = sum(line.lower().split().count('the') for line in f_obj)
print(total)

关于python - 使用count方法统计文本文件中的某个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38680111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com