假设我有一个诅咒词列表
curseword = ['fuxx', 'die', 'damn']
如果我要遍历句子列表(字符串列表)以检查句子中是否包含诅咒词。
text = [ ['i','am','a','boy'] , [....] , [....] ]
我试图做类似的事情
for i in curse_words:
for t in text:
if i in t:
// exsits
但它似乎是错误且效率低下的。
我如何有效地做到这一点?
将您的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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句