试图确保某些符号不在一个词中

2024-10-06 11:19:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在有以下用方括号和普通括号过滤单词的方法,我忍不住想一定有更整洁的方法

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)

但在我的脑子里似乎有点杀伤力。我很感激我是一个新手程序员,所以我能做的任何事情都会非常有帮助


Tags: and方法in列表forifnotrandom
2条回答

我不确定要过滤什么,但我建议您使用python的Regular expression模块

import re

r = re.compile("\w*[\[\]\(\)]+\w*")
test = ['foo', '[bar]', 'f(o)o']

result = [word for word in test if not r.match(word)]
print result

输出为['foo']

使用“设置交点”

brackets = set("[]()")
words = [word for word in random.choice(headlines).split(" ")[1:-1] if not brackets.intersection(word)]

如果word不包含brackets中的任何字符,则交集为空

您还可以考虑使用itertools而不是列表理解

words = list(itertools.ifilterfalse(brackets.intersection,
                                    random.choice(headlines).split(" "))[1:-1]))

相关问题 更多 >