-2

我想要的程序必须读取这样的文本文件:

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

并运行以下输出:

WESTS 3
EASTS 1

我想我需要先把它分组。删除换行符。然后删除第一行中除大写字母之外的所有内容,并将它们分配给单独的变量。然后在文本中搜索这些变量出现的数量。所以这意味着 a = 2 和 b = 4 然后 - 每个总数减 1 并将其作为结果。这是我到目前为止所拥有的:

import string
teams = []
for word in open('commentary.txt'):
  word = word[:-1] # gets away the /n characters.
  word = word.strip("versus") # This line doesn't work
  teams.append(word)
print(teams)

我想我知道该怎么做,但我不知道......任何帮助将不胜感激:D谢谢

4

2 回答 2

0

您需要为此使用字典或计数器。像这样的东西。

 from collections import Counter
 counter = Counter()
 for line in file:
     if 'versus' in line:
         continue
     words = line.split()
     counter[words[0]] += 1

 for team in counter:
     print team, counter[team]
于 2013-08-09T09:45:12.883 回答
0

尝试查看字符串方法count。我会加入文件中的行,然后计算 EAST 和 WEST 在其中出现的次数。

示例代码可能是这样的:

def countwords(filename):
    with open(filename) as f:
        file_list = list(f)
        split_first_line = file_list[0].split()
        teams = (split_first_line[0], split_first_line[-1])
        for team in teams:
            print("{} {}".format(team, "".join(file_list[1:]).count(team)))
于 2013-08-09T09:46:23.377 回答