简体   繁体   中英

If a certain word is not before the search word then add to list python

I would like the program to detect whether a certain word is before the search word and if it is not to add it to a list.

This is what I have come up with myself:

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)

The excpected output is ["take"], but it remains the same with ["take, "take]

Watch how it should be formulated: gather all take word occurrences that aren't preceded with word 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)

The output:

['take']

It may be simpler to first convert you sentence to a list of words.

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM