Python从字符串中删除单词

时间:2013-08-09 09:35:48

标签: python string list replace

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

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 感谢

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分:0)

尝试查看字符串方法count。我会join文件中的行,然后计算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)))