简体   繁体   中英

Python: Counting Occurrences of a Word From a txt file with Input

I am new to programming and I need help finding how many times the user input occurs inside of a txt file. The code I currently have is:

myfile = open("WorldSeriesWinners.txt")

count = 0
team = input("Enter in the team name that won the world series: ")
line = myfile.readline()

myfile.readline()

while team in line:
    count += 1

myfile.readline()

print("The", team, "won the world series", count, "times")



myfile.close()

The output I get from this is:

Enter in the team name that won the world series: New York Yankees
The New York Yankees won the world series 0 times

How would I get it to show many times a specific team won? Thanks in advance.

team = input('Enter team name: ')
count = 0
with open("WorldSeriesWinners.txt") as f:
    for line in f:
        if team in line:
            count += 1

print('{} won the world series {} times'.format(team, count)

Go through line by line and check each line using if statements

Try the following:

import re

def world_series_count(team):
    with open("WorldSeriesWinners.txt") as f:
        data = f.read()
        items = re.findall(team, data)
    return len(items)

team = input('Enter a team name: ')

count = world_series_count(team)

print('{} won the world series {} times'.format(team, count))

Why are you people complicating matters way over necessary.

This will count occurrences of text in a txt file given by path, regardless of text formatting (unless it is hyphenized):

def count_in_file (path, text):
    f = open(path, "rb")
    c = f.read()
    f.close()
    return " ".join(c.split()).count(text.strip())

A little tweak will be needed to support unicode txt files. But there. Simple and easy.

If the txt file is extremely big, then perform this using buffering with static chunk size:

def count_in_file (path, text, chunksize=4096):
    text = text.strip()
    f = open(path, "rb")
    f.seek(0, 2)
    fsize = f.tell()
    f.seek(0)
    if fsize<=chunksize:
        c = f.read()
        f.close()
        return " ".join(c.split()).count(text)
    count = 0
    l = len(text)
    c = f.read(chunksize)
    r = c[-l:]
    while c:
        count += " ".join(c.split()).count(text)
        if r!=text: f.seek(f.tell()-l+1)
        c = f.read(chunksize)
        r = c[-l:]
    f.close()
    return count

Well, this now is a bit complicated. But if a file is really, really big, and it is formatted over lines, this is a good way to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM