【问题标题】:python 3.4 Counting occurrences in a .txt filepython 3.4 计算 .txt 文件中的出现次数
【发布时间】:2014-06-07 13:47:53
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    您无需手动检查文件计数行。你可以使用.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: ")))
    

    【讨论】:

    • 谢谢,但是如何计算像(“新文件夹”)这样的短语
    【解决方案2】:

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

    while lst != ''
    

    你可以试试

    for line in teams:
        if who in line:
            count += 1
    

    【讨论】:

    • 我在第一行将计数初始化为 0 {count = 0} 这是不是放置不当?我认为它最好作为一个全局变量。
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 2017-10-28
      • 2022-01-18
      相关资源
      最近更新 更多