1

I want to remove a list of words/phrases in a sentence.

sentence = 'hello thank you for registration'
words_to_remove=['registration','reg','is','the','in','payment','thank you','see all tags']

sentence = ' '.join([word for word in sentence.split() if word not in words_to_remove]) 

But this does not remove 'thank you' or 'see all tags'

Thanks

3 Answers 3

0

Iterate over the list of words and replace each word using str.replace():

sentence = 'hello thank you for registration'
words_to_remove=['registration','reg','is','the','in','payment','thank you','see all tags']

for word in words_to_remove:
    sentence = sentence.replace(word, '')

At the end, senctence will hold the value:

>>> sentence
'hello  for '
Sign up to request clarification or add additional context in comments.

6 Comments

I took ur answer because it was the earliest
@weizengJust for your info, you should not be accepting the answer which was earliest, but the one which best suits your problem and detailed information as it acts a reference for others referring in the future. Looks like here my answer satisfies those clauses as well ;)
Can add sentence = ' '.join(sentence.split()) at the end to tidy up extra space left from remove words
@Skycc Just for removing the space why .join() and .split()? do just str.strip()
Strip only remove both end space but not in the middle
|
0
for word in words_to_remove:
    sentence = sentence.replace(word, "")

1 Comment

Yes I think this is what im looking for
0

Split 'thank you' in 'thank','you', because that happens when you split sentence.

>>> sentence = 'hello thank you for registration'
>>> words_to_remove=['registration','reg','is','the','in','payment','thank','you','see all tags']
>>> sentence = ' '.join([word for word in sentence.split() if word not in words_to_remove])
>>> sentence
'hello for'
>>>

1 Comment

I dont want to delete all the "you"... etc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.