[英]If a certain word is not before the search word then add to list python
我希望該程序檢測某個單詞是否在搜索單詞之前,以及是否不將其添加到列表中。
這是我自己想到的:
sentence = "today i will take my dog for a walk, tomorrow i will not take my dog for a walk"
all = ["take", "take"]
all2= [w for w in all if not(re.search(r'not' + w + r'\b', sentence))]
print(all2)
預期的輸出為[“ take”],但與[“ take,” take]相同
看着它應該如何制定: 收集所有take
未使用前逐字逐句出現not
:
import re
sentence = "today i will take my dog for a walk, tomorrow i will not take my dog for a walk"
search_word = 'take'
all_takes_without_not = re.findall(fr'(?<!\bnot)\s+({search_word})\b', sentence)
print(all_takes_without_not)
輸出:
['take']
首先將您的句子轉換為單詞列表可能會更簡單。
from itertools import chain
# Get individual words from the string
words = sentence.split()
# Create an iterator which yields the previous word at each position
previous = chain([None], words)
output = [word for prev, word in zip(previous, words) if word=='take' and prev != 'not']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.