我现在有以下用方括号和普通括号过滤单词的方法,我忍不住想一定有更整洁的方法
words = [word for word in random.choice(headlines).split(" ")[1:-1] if "[" not in word and "]" not in word and "(" not in word and ")" not in word]
我试着创建一个符号列表或元组
if symbol not in word
但是它死了,因为我把一个列表和一个字符串进行比较。我很感激我能把它分解出来做一个比较,比如:
for word in random.choice(headlines).split(" ")[1:-1]:
popIn = 1
for symbol in symbols:
if symbol in word:
popIn = 0
if popIn = 1:
words.append(word)
但在我的脑子里似乎有点杀伤力。我很感激我是一个新手程序员,所以我能做的任何事情都会非常有帮助
我不确定要过滤什么,但我建议您使用python的Regular expression模块
输出为['foo']
使用“设置交点”
如果
word
不包含brackets
中的任何字符,则交集为空您还可以考虑使用
itertools
而不是列表理解相关问题 更多 >
编程相关推荐