51

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?

2
  • If you want to do full word match, you should be splitting the query to a list, and search. query.split()
    – karthikr
    Aug 17, 2014 at 3:28
  • Is there a way to do this using a regex? Aug 15, 2020 at 3:53

6 Answers 6

81

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.

7
  • This does work! Can you please explain what the 4th line does? I am getting a bit confused with it. Aug 17, 2014 at 4:23
  • 1
    It creates a new list with all the words of which the lower-case variant is not found in stopwords. Aug 17, 2014 at 4:48
  • 2
    @RohitShinde: It's a list comprehension. Aug 17, 2014 at 5:40
  • @RobbyCornelissen works just with words but if you had a stopword which would be like ['what about this','what about that'] and your query would be "Hello just try to remove what about this or what about that", it won't work.
    – DevMan
    Aug 10, 2022 at 13:56
  • 1
    this works well in languages that use space to separate vocabularies. For some languages like Chinese, this does not work.
    – Raptor
    Mar 9 at 6:11
16

the accepted answer works when provided a list of words separated by spaces, but that's not the case in real life when there can be punctuation to separate the words. In that case re.split is required.

Also, testing against stopwords as a set makes lookup faster (even if there's a tradeoff between string hashing & lookup when there's a small number of words)

My proposal:

import re

query = 'What is hello? Says Who?'
stopwords = {'what','who','is','a','at','is','he'}

resultwords  = [word for word in re.split("\W+",query) if word.lower() not in stopwords]
print(resultwords)

output (as list of words):

['hello','Says','']

There's a blank string in the end, because re.split annoyingly issues blank fields, that needs filtering out. 2 solutions here:

resultwords  = [word for word in re.split("\W+",query) if word and word.lower() not in stopwords]  # filter out empty words

or add empty string to the list of stopwords :)

stopwords = {'what','who','is','a','at','is','he',''}

now the code prints:

['hello','Says']
0
11

building on what karthikr said, try

' '.join(filter(lambda x: x.lower() not in stopwords,  query.split()))

explanation:

query.split() #splits variable query on character ' ', e.i. "What is hello" -> ["What","is","hello"]

filter(func,iterable) #takes in a function and an iterable (list/string/etc..) and
                      # filters it based on the function which will take in one item at
                      # a time and return true.false

lambda x: x.lower() not in stopwords   # anonymous function that takes in variable,
                                       # converts it to lower case, and returns true if
                                       # the word is not in the iterable stopwords


' '.join(iterable) #joins all items of the iterable (items must be strings/chars)
                   #using the string/char in front of the dot, i.e. ' ' as a joiner.
                   # i.e. ["What", "is","hello"] -> "What is hello"
5
  • I tried what you said. It is giving me an error saying that argument of type function is not iterable. Aug 17, 2014 at 3:58
  • Can you explain me what the line does? Aug 17, 2014 at 4:21
  • why are you using list and split(' ')? Aug 17, 2014 at 4:54
  • i didn't originally use list, it was an edit, i wasn't sure why he was getting an error. put it in thinking maybe his filter object couldn't be used as an iterable in an older version or something. split is there to seperate the string into words
    – pseudonym
    Aug 17, 2014 at 4:57
  • yes but you don't need to specify ' ', try splitting 'What is hello' Aug 17, 2014 at 5:03
8

Looking at the other answers to your question I noticed that they told you how to do what you are trying to do, but they did not answer the question you posed at the end.

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

wht s llo

Why does this happen?

This happens because .replace() replaces the substring you give it exactly.

for example:

"My, my! Hello my friendly mystery".replace("my", "")

gives:

>>> "My, ! Hello  friendly stery"

.replace() is essentially splitting the string by the substring given as the first parameter and joining it back together with the second parameter.

"hello".replace("he", "je")

is logically similar to:

"je".join("hello".split("he"))

If you were still wanting to use .replace to remove whole words you might think adding a space before and after would be enough, but this leaves out words at the beginning and end of the string as well as punctuated versions of the substring.

"My, my! hello my friendly mystery".replace(" my ", " ")
>>> "My, my! hello friendly mystery"

"My, my! hello my friendly mystery".replace(" my", "")
>>> "My,! hello friendlystery"

"My, my! hello my friendly mystery".replace("my ", "")
>>> "My, my! hello friendly mystery"

Additionally, adding spaces before and after will not catch duplicates as it has already processed the first sub-string and will ignore it in favor of continuing on:

"hello my my friend".replace(" my ", " ")
>>> "hello my friend"

For these reasons your accepted answer by Robby Cornelissen is the recommended way to do what you are wanting.

0
" ".join([x for x in query.split() if x not in stopwords])
-1
stopwords=['for','or','to']
p='Asking for help, clarification, or responding to other answers.'
for i in stopwords:
  n=p.replace(i,'')
  p=n
print(p)
2
  • Although this code might solve the problem, a good answer should explain what the code does and how it helps
    – BDL
    Aug 24, 2020 at 8:17
  • This code will do exactly the same thing the question is asking about. It neither resolves the problem nor explains why it is not doing what they want.
    – B.Adler
    Oct 21, 2022 at 16:27

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.