python 3.4 Counting occurrences in a .txt file

本小妞迷上赌 提交于 2020-01-13 18:07:08

问题


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!

here is my code

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

回答1:


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

count = lst.count(who)

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

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

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: ")))



回答2:


According to the docs :https://docs.python.org/3/library/io.html#io.IOBase.readline, readline returns single line, so in your program you have infinite loop with first line of the file

while lst != ''

You can try something like

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


来源:https://stackoverflow.com/questions/23232248/python-3-4-counting-occurrences-in-a-txt-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!