假設我有一個串列串列。
List1=[["Red is my favorite color."],["Blue is her favorite."], ["She is really nice."]]
現在我想檢查在一組詞之后是否存在“is”這個詞。
我說了一句話
word_list=['Red', 'Blue']
有沒有辦法檢查使用 if 陳述句?
如果我寫
if 'is' in sentences:
它將回傳 List1 中的所有三個句子,我希望它回傳前兩個句子。
有沒有辦法檢查單詞“is”是否正好位于 word_list 中的單詞之后?先感謝您。
uj5u.com熱心網友回復:
注意。我假設在字串的開頭匹配。對于任何地方的匹配,請使用re.search而不是re.match.
您可以使用正則運算式:
import re
regex = re.compile(fr'\b({"|".join(map(re.escape, word_list))})\s is\b')
# regex: \b(Red|Blue)\s is\b
out = [[bool(regex.match(x)) for x in l]
for l in List1]
輸出:[[True], [True], [False]]
使用的輸入:
List1 = [['Red is my favorite color.'],
['Blue is her favorite.'],
['She is really nice.']]
word_list = ['Red', 'Blue']
如果你想要句子:
out = [[x for x in l if regex.match(x)]
for l in List1]
輸出:
[['Red is my favorite color.'],
['Blue is her favorite.'],
[]]
或作為平面串列:
out = [x for l in List1 for x in l if regex.match(x)]
輸出:
['Red is my favorite color.',
'Blue is her favorite.']
uj5u.com熱心網友回復:
你可以試試這個:
List1 = [['Red is my favorite color.'],['Blue is her favorite.'], ['She is really nice.']]
listResult = []
word_list = ['Red', 'Blue']
for phrase in List1:
for word in word_list:
if f'{word} is' in phrase[0]:
listResult.append(phrase[0])
uj5u.com熱心網友回復:
已經回答了。
請參閱重新模塊檔案:https ://docs.python.org/3/library/re.html
堆疊溢位先前回答的問題:檢查字串是否匹配模式
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/504646.html
下一篇:回圈塊DOM操作
