我試圖計算單詞'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與它本身,它仍然給我零這兩本書。 –