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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With