python 3.4计算.txt文件中的出现次数

时间:2014-04-22 23:43:48

标签: python-3.x counter find-occurrences

我正在写一个简单的"我正在上课的小程序。这应该问我要搜索哪个团队,然后返回它在.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()

3 个答案:

答案 0 :(得分:6)

您不需要手动浏览文件计数行。您可以使用.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: ")))

答案 1 :(得分:0)

根据文档:https://docs.python.org/3/library/io.html#io.IOBase.readlinereadline返回单行,因此在您的程序中,您将无限循环文件的第一行

while lst != ''

您可以尝试类似

的内容
for line in teams:
    if who in line:
        count += 1

答案 2 :(得分:0)

如果你不介意小写或大写,你可以使用@charles-clayton 回复的这个修改版本!

print(open('WorldSeriesWinners.txt', 'r').read().lower().count(input("Enter team name: ").lower()))