我试图计算单词'the'出现在保存为文本文件的两本书中的次数。我正在运行的代码会为每本书返回零。使用count方法来计算文本文件中的某个单词
这里是我的代码:
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之前我增加它。所以我添加了第二行增加word_count与它本身,它仍然给我零这两本书。 –