Skip to main content
 首页 » 编程设计

python-3.x之python 3.4 计算 .txt 文件中的出现次数

2025年12月25日42tuyile006

我正在为我正在类的类(class)编写一个“简单”的小程序。这应该问我要搜索哪个团队,然后返回它在 .txt 文件中的列表中出现的次数。它像它应该的那样请求输入,并且似乎运行得很好!它现在已经运行了一个小时 :) 我没有收到任何错误,它似乎陷入了一个循环。
预先感谢大家的帮助!

这是我的代码

count = 0 
 
def main(): 
# open file 
    teams = open('WorldSeriesWinners.txt', 'r') 
# get input 
    who = input('Enter team name: ') 
#begin search 
    lst = teams.readline() 
    while lst != '': 
        if who in lst: 
            count += 1 
 
teams.close() 
print(count) 
 
main() 

请您参考如下方法:

您无需手动检查文件计数行。您可以使用 .read() :

count = lst.count(who) 

另一个问题是您正在调用 teams.close()print(count)函数之外。

这意味着他们会在您调用 main 之前尝试执行,并且您正在尝试关闭尚未打开或定义的“团队”,因此您的代码不知道该做什么。打印计数也是如此 - 尚未在函数之外定义计数,尚未调用该函数。

如果你想在函数外使用它们,你需要在函数的末尾 return count
此外,在您的循环中,您正在执行语句 count += 1这意味着 count = count + 1 ,但你没有告诉它第一次运行时计数是多少,所以它不知道应该添加什么。通过定义 count = 0 来解决这个问题在函数内部的循环之前。

你有一个无限循环的原因是你的条件永远不会得到满足。你的代码永远不应该花费一个小时来执行,就像,几乎永远不会。不要让它运行一个小时。

这是一些替代代码。确保你理解这些问题。
def main(): 
 
    file  = open('WorldSeriesWinners.txt', 'r').read() 
    team  = input("Enter team name: ") 
    count = file.count(team) 
 
    print(count) 
 
main() 

您可以从字面上将整个程序放在一行中:
print(open('WorldSeriesWinners.txt', 'r').read().count(input("Enter team name: ")))