我们如何高效地检查一个字符串列表是否包含另一个字符串列表中的单词?

2024-05-16 00:40:31 发布

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

我应该有一份诅咒者的名单吗

curseword = ['fuxx', 'die', 'damn']

如果我遍历一个句子列表(字符串列表)来检查这个句子是否包含诅咒词。你知道吗

text = [ ['i','am','a','boy'] , [....] , [....] ]

我试着做一些

for i in curse_words:
    for t in text:
        if i in t:
            // exsits

但这似乎是错误和低效的。你知道吗

我怎样才能有效地做到这一点?你知道吗


Tags: 字符串textin列表foram句子words
3条回答

就像你说的你想要不同的东西:

You can try without loop:

curseword = ['fuxx', 'die', 'damn']
text = [ ['i','am','a','damn','boy']]

print(list(filter(lambda z:z!=[None],map(lambda x:(list(map(lambda y:y if x in y else None,text))),curseword))))

输出:

[[['i', 'am', 'a', 'damn', 'boy']]]

您可以将cursewords强制转换为set,以提高查找效率,并使用列表理解,在较小的情况下比更通用的循环更有效:

curseword = {'fuxx', 'die', 'damn'}
text = [ ['i','am','a','boy'] , [....] , [....] ]
new_text = map(int, [all(b not in curseword for b in i) for i in text])

curseword列表转换为一个集合,然后用户set.intersection检查句子中的单词是否与cursword重叠。你知道吗

In [10]: curseword = {'fuxx', 'die', 'damn'}

In [11]: text = [ ['i','am','a','boy'], ['die']]

In [21]: new_text = [int(bool(curseword.intersection(sent))) for sent in text]

In [22]: new_text
Out[22]: [0, 1]

相关问题 更多 >