[英]How can we efficiently check whether a list of string contains a word from another list of strings?
假設我有一個詛咒詞列表
curseword = ['fuxx', 'die', 'damn']
如果我要遍歷句子列表(字符串列表)以檢查句子中是否包含詛咒詞。
text = [ ['i','am','a','boy'] , [....] , [....] ]
我試圖做類似的事情
for i in curse_words:
for t in text:
if i in t:
// exsits
但它似乎是錯誤且效率低下的。
我如何有效地做到這一點?
您可以將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]
如您所說,您想要一些不同的東西:
您可以嘗試不使用循環:
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']]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.