【问题标题】:Python removing words from strings [duplicate]Python从字符串中删除单词[重复]
【发布时间】:2013-08-11 04:59:36
【问题描述】:

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

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

【问题讨论】:

  • 为什么要导入字符串?您没有使用该模块
  • 嗯,这是一个无意的重复。另外,我似乎遇到了不同的问题。
  • 我认为您的意见不清楚,需要完善。

标签: python string list replace


【解决方案1】:

尝试查看字符串方法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)))

【讨论】:

    【解决方案2】:

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

     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]
    

    【讨论】:

      猜你喜欢
      • 2012-03-14
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      • 1970-01-01
      • 2019-11-29
      • 1970-01-01
      相关资源
      最近更新 更多