0

The code I'm trying to write, is supposed to read a text file, and check how many times, 'EASTS', or 'WESTS' have scored, I can fetch the numbers by using find and 'EASTS' or 'WESTS'. But instead of getting the occurrence, I get how many times it exists in each line.

So:

1 
 1
 1
 1

(and idk why there is space before the 1's that belong to the wests')

Here is the text:

EASTS versus WESTS
EASTS have scored 25:13
WESTS have scored 26:38
WESTS have scored 40:23
WESTS have scored 42:01

And here is my code, what am I doing wrong?

name = "scores.txt"

with open(name) as f:
    ff = f.readlines()[1:]
    for line in ff:
        words = line.split()
        a = words.count('EASTS')
        b = words.count('WESTS')
        a_ = str(a)
        b_ = str(b)
        eas =  a_.strip('0')
        wes =  b_.strip('0')
        print(eas, wes)

The result should look something like this

WESTS 3
EASTS 1

Can somebody help? Thank you in advance!

4

1 回答 1

0

Initialize variables (wests, easts) as 0. Increment 1 in a loop. Print result.

import itertools

team1, team2 = 'WESTS', 'EASTS'
count1, count2 = 0, 0
with open('scores.txt') as f:
    for line in itertools.islice(f, 1, None):
        if line.startswith(team1):
            count1 += 1
        else:
            count2 += 1
    print(team1, count1)
    print(team2, count2)

Get team names at runtime

with open('scores.txt') as f:
    team1, _, team2 = next(f).split()
    count1, count2 = 0, 0
    for line in f:
        if line.startswith(team1):
            count1 += 1
        else:
            count2 += 1
    print(team1, count1)
    print(team2, count2)
于 2013-08-09T07:32:29.253 回答