[英]Counting instances of words from a file in Python, only works for single letters
下面的代码应该计算文本文件中特定单词的实例,尽管它似乎仅适用于单个字母。 使用两个或两个以上字母的字符串总是返回0。我已经检查过了,对于给定的文件,我一直在使用的输入绝对不应该返回0。
有任何想法吗?
def count_of_word(filename, word_to_count):
"""Counts instances of a particular word in a file"""
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
print("File " + filename + " not found")
else:
word_count = contents.lower().count(word_to_count)
print("The count of the word '" + word_to_count + "' in " + filename + " is " + str(word_count))
您将小写字母更改为仅文件输入。 尝试:
word_count = contents.lower().count(word_to_count.lower())
这对我的作品-我得到1026的计数and
您参考的文件中。
编辑:怀疑编码问题,所以建议指定编码,它可以工作:
open(filename, encoding='utf_8')
并没有更改代码中的一行,并且它起作用了,我想知道这是否与您如何将'the'
或'and'
传递到函数中有关,应该是count_of_word('alice.txt', 'the')
def count_of_word(filename, word_to_count):
"""Counts instances of a particular word in a file"""
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
print("File " + filename + " not found")
else:
word_count = contents.lower().count(word_to_count)
print("The count of the word '" + word_to_count + "' in " + filename + " is " + str(word_count))
count_of_word('alice.txt', 'the')
count_of_word('alice.txt', 'a')
~/python/stack/sept/twenty_2$ python3.7 alice.py The count of the word 'and' in alice.txt is 2505 The count of the word 'a' in alice.txt is 9804
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.