Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing list of words from a string

Tags:

python

string

I have a list of stopwords. And I have a search string. I want to remove the words from the string.

As an example:

stopwords=['what','who','is','a','at','is','he'] query='What is hello' 

Now the code should strip 'What' and 'is'. However in my case it strips 'a', as well as 'at'. I have given my code below. What could I be doing wrong?

for word in stopwords:     if word in query:         print word         query=query.replace(word,"") 

If the input query is "What is Hello", I get the output as:
wht s llo

Why does this happen?

like image 521
Rohit Shinde Avatar asked Aug 17 '14 03:08

Rohit Shinde


People also ask

How do I remove a set of words from a string in Python?

Remove a Word from String using replace() print("Enter String: ", end="") text = input() print("Enter a Word to Delete: ", end="") word = input() wordlist = text. split() if word in wordlist: text = text.

How do I remove a list of words from a list in Python?

The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.

How do you remove text from a string in Python?

You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.


1 Answers

This is one way to do it:

query = 'What is hello' stopwords = ['what', 'who', 'is', 'a', 'at', 'is', 'he'] querywords = query.split()  resultwords  = [word for word in querywords if word.lower() not in stopwords] result = ' '.join(resultwords)  print(result) 

I noticed that you want to also remove a word if its lower-case variant is in the list, so I've added a call to lower() in the condition check.

like image 95
Robby Cornelissen Avatar answered Sep 24 '22 23:09

Robby Cornelissen