根据特定字符串设置列表

时间:2017-12-23 23:38:22

标签: python regex string text

我正在阅读文件并为其分配变量" input_kws"。

input_kws = open('words.txt','r')

" input_kws"的内容是:

baseball
basketball
football
tennis
boxing
volleyball

我只是想创建一个新列表,其中只包含包含" ball"。

的单词

2 个答案:

答案 0 :(得分:3)

只是检查球是否'在每个字符串中。

input_kws= 'baseball basketball football tennis'.split()

ball_sports = [word for word in input_kws if 'ball' in word]
>>>['baseball', 'basketball', 'football']

或者,您可以使用filter来获得相同的结果

f = filter(lambda x: 'ball' in x, input_kws) #Returns a generator
ball_sports = list(f)

如果生成器不是你的东西,你可以随时使用循环

ball_sports = []
for sport in input_kws:
    if 'ball' in sport:
        ball_sports.append(sport)

如果您的列表中有其他体育项目具有子字符串'则会失败。实施例

input_kws= 'baseball basketball football tennis balloon'.split()
f = filter(lambda x: 'ball' in x, input_kws) #Returns a generator
ball_sports = list(f)
>>>['baseball', 'basketball', 'football','balloon']

答案 1 :(得分:0)

使用也可以使用正则表达式在字符串中查找球

import re

for line in open(r"words.txt","r"):
    if re.findall(r"ball",line) ==["ball"]:
        print(line)

baseball

basketball

football

volleyball