Skip to main content
 首页 » 编程设计

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

2025年05月04日28shanyou

我正在尝试计算单词“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)