The errors you have (besides my other comments) are because you're modifying a list while iterating over it. But you take the length of the list at the start, thus, after you've removed some elements, you cannot access the last positions.
I would do it this way:
words = ['a', 'b', 'a', 'c', 'd']
stopwords = ['a', 'c']
for word in list(words): # iterating on a copy since removing will mess things up
if word in stopwords:
words.remove(word)
An even more pythonic way using list comprehensions:
new_words = [word for word in words if word not in stopwords]
Answer from Francis Colas on Stack OverflowThe errors you have (besides my other comments) are because you're modifying a list while iterating over it. But you take the length of the list at the start, thus, after you've removed some elements, you cannot access the last positions.
I would do it this way:
words = ['a', 'b', 'a', 'c', 'd']
stopwords = ['a', 'c']
for word in list(words): # iterating on a copy since removing will mess things up
if word in stopwords:
words.remove(word)
An even more pythonic way using list comprehensions:
new_words = [word for word in words if word not in stopwords]
As an observation, this could be another elegant way to do it:
new_words = list(filter(lambda w: w not in stop_words, initial_words))
I have a list of strings:
list_strings = ['[power, brilliant, evil]', '[shock, poetic, watch, lift]']
I want to remove words that occur in the following list:
remove = ['evil', 'money', 'poetic', 'lift']
The result I am seeking is:
result = ['[power, brilliant]', '[shock, watch]']
It's also important that the words that remain stay in a list themselves e.g., [power, brilliant].
What I have tried:
# attempt 1:
list_strings = ['[power, brilliant, evil]', '[shock, poetic, watch, lift]']
remove = ['evil', 'money', 'poetic', 'lift']
result = [' '.join(w for w in str(list_strings).split() if w.lower() not in remove)
for place in places
]
print(result)
# attempt 2:
list_strings = ['[power, brilliant, evil]', '[shock, poetic, watch, lift]']
remove = ['evil', 'money', 'poetic', 'lift']
for each in list_strings:
for i in remove:
x = each.replace(i, "")
print(x)Removing words from list in python - Stack Overflow
web scraping - Removing words from python lists? - Stack Overflow
string - Python script for removing words with certain letters in a list - Stack Overflow
Python- How To Remove Elements From a List Containing a Specific Word - Stack Overflow
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.
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']
You need to split each phrase into words and re-join the words into phrases after filtering out those in stop.
[' '.join(w for w in p.split() if w not in stop) for p in abc]
This outputs:
['issues in performance', 'how are you doing', 'hey my name is abc, what is your name', 'pleased', 'compliance installed']
Here is a solution, using simple regular expression with the re.sub method. This solution removes numbers as well.
import re
abc=[ 'issues in performance 421',
'how are you doing',
'hey my name is abc, 143 what is your name',
'attention pleased',
'compliance installed 234']
stop=['attention\s+', 'installed\s+', '[0-9]']
[(lambda x: re.sub(r'|'.join(stop), '', x))(x) for x in abc]
'Output':
['issues in performance ',
'how are you doing',
'hey my name is abc, what is your name',
'pleased',
'compliance ']
Using list comprehension we can easily accomplish this goal. Also using in we can check if a key word is in any elements in the given list.
list1= [ 'one', 'one-test', 'two', 'two-test', 'three', 'three-test']
newList = [elements for elements in list1 if '-test' not in elements]
output
['one', 'two', 'three']
Use list comprehension and check if the element of the list contains -test during iteration.
remove = '-test'
list1= [ 'one', 'one-test', 'two', 'two-test', 'three', 'three-test']
[x for x in list1 if remove not in x]
#['one', 'two', 'three']
The problem is the for loop of python.
For example: if you do like this:
arr = range(1, 10)
for x in arr:
print x
arr.remove(x)
Then you will see that not all item in arr was removed.
In your case, we can do like this:
newDoc = [ word for word in doc if len(word) >= 3 ]
Welcome to python.
In order to accurately answer your question, we need to see what the contents of doc are. Preferably in the format it is displayed in the interactive Python interpreter.
That being said, the ideal (read pythonic) way to remove items from a list would be to A) use filter:
filter(lambda x: len(x) > 2, doc)
or B) use a list comprehension:
[word for word in doc if len(word) > 2]
I am making my first hangman game, I finished everything and now I want to add lots of words to a txt file and import them to the hangman file. I came against a problem however, some of the words I copied and pasted were short and so I wanted to create a small function that deletes all the short word in the Long string.
I started by making the list of words into an actual list
hang = words.split() #now all my words are in a list, then...
for item in hang:
if len(item) < 2:
hang.remove(item)
print(hang) #perfect all the short words have been removed.
#But now I want to change the hang from being a type list to a normal list of words in string, not an actual list.
Is there a way I can do that exactly?Thank you.
You can use a regular expression with word boundaries.
pattern = re.compile('|'.join(rf'\b{re.escape(w)}\b' for w in word_list))
def remove_w(text):
return pattern.sub('', text)
Alternatively, use str.split to separate into words delimited by spaces, remove the words exactly matching one of those in the set, then join it back together.
def remove_w(text):
return ' '.join(w for w in text.split() if w not in word_list)
You can use regular expressions to remove whole words from the text while taking care not to remove parts of other words. In your specific case, you can use the re module to achieve that:
import re
word_list = {"the", "mind", "pen"}
word_pattern = r"(\s?)\b(?:" + "|".join(re.escape(word) for word in word_list) + r")\b"
pattern = re.compile(word_pattern)
def remove_w(text):
return pattern.sub("", text)
text = "A pencil is over a thermometer with mind itself."
result = remove_w(text)
print(result)
The output will be:
A pencil is over a thermometer with itself.
Explanation:
re.escape(word): Escapes any characters that might have a special meaning in regular expressions, like.,?,*, etc.(\s?): Matches any whitespace and?to make it optional.'|'.join(...): Joins the words together with the regex OR pattern|.\b: Matches the empty string but only at the beginning or end of a word.pattern.sub('', text): Replaces the matched words in the text with an empty string.
This approach should work efficiently even for large articles, as the regular expression engine is optimized for text processing tasks like these.