python 3.4计算.txt文件中的出现次数 [英] python 3.4 Counting occurrences in a .txt file

查看:124
本文介绍了python 3.4计算.txt文件中的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为正在参加的课程编写一个简单的小程序。应该问我要搜索什么团队,然后返回出现在.txt文件列表中的次数。它要求输入应有的值,并且看起来运行得很好!它已经运行了一个小时了:)我一点都没有收到错误,它似乎陷入了循环。
预先感谢大家的帮助!

I am writing a "simple" little program for a class i am taking. this is supposed ask me for what team to search for and then return the number of times it appears on the list in a .txt file. it requests input like it should and seems to run great! its been running for an hour now :) i am getting no errors at all it seems to be stuck in a loop. thank you all in advance for your help!

这是我的代码

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()

You don't need to go through the file counting lines manually. You can just use .read():

count = lst.count(who)

另一个问题是您正在呼叫团队。函数外部的close() print(count)

The other problem is that you're calling teams.close() and print(count) outside of the function.

他们会在调用main之前尝试执行,并且试图关闭尚未打开或尚未定义的团队,因此您的代码不知道该怎么做。打印计数也一样-计数尚未在函数外部定义,因此尚未调用。

That means they'll try to execute before you call main, and you're trying to close 'teams' which hasn't been opened or defined yet, so your code doesn't know what to do. The same is with printing count - count hasn't been defined outside of the function, which hasn't been called.

如果要在函数外部使用它们,在函数末尾,您需要返回计数

If you want to use them outside the function, at the end of the function you need to return count

此外,在循环中,您正在执行语句 count + = 1 ,这意味着 count = count + 1 ,但是您没有告诉它什么是第一次运行,因此它不知道应该添加什么。通过在函数内部循环之前定义 count = 0 来解决此问题。

Also, in your loop, you're executing the statement count += 1 which means count = count + 1, but you haven't told it what count is the first time it runs, so it doesn't know what it should add to one. Fix this by defining count = 0 before the loop inside the function.

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

And the reason you have an infinite loop is because your condition will never be satisfied. Your code should never take an hour to execute, like, pretty much never. Don't just leave it running for an hour.

这里有一些替代代码。

Here's some alternative code. Make sure you understand the problems though.

def main():

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

    print(count)

main()

您可以将整个程序直接放入一行:

You can literally put this entire program into one line:

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

这篇关于python 3.4计算.txt文件中的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆