[英]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.