You can use a list comprehension with an if-else.
list_A = ['hello', 'world', 'goodbye', 'world']
list_B = [word if word != 'world' else 'friend' for word in list_A]
You now have a new list, list_B, where all instances of the word "world" have been replaced with "friend".
pandas - How to replace words in list with Python - Stack Overflow
How Do I Replace Words In a String With Items In a List In Python - Stack Overflow
How to replace a word found in a string with what is in the list in Python - Stack Overflow
text - Replace all words from word list with another string in python - Stack Overflow
You can use a list comprehension with an if-else.
list_A = ['hello', 'world', 'goodbye', 'world']
list_B = [word if word != 'world' else 'friend' for word in list_A]
You now have a new list, list_B, where all instances of the word "world" have been replaced with "friend".
If you have unique values in your list:
my_list[my_list.index('old_word')]='new_word'
Iterate over the invalid_list and use the in-built replace() function to replace the substring.
for i in invalid_list:
s = [string.replace(i, 'xyz') for string in s]
Looping over the items of invalid_list is inefficient. This increases the complexity of the algorithm.
An efficient solution would be to use a regex to search motifs in each string only once:
s = ['123xyz', '456xye','789xyf']
invalid_list = ['xye','xyf']
import re
regex = re.compile('|'.join(map(re.escape, invalid_list)))
s2 = [regex.sub('xyz', x) for x in s]
Output:
['123xyz', '456xyz', '789xyz']
avoid matching partial words:
s = ['123xyz', '456xye','789xyf']
invalid_list = ['xy','xye','xyf']
import re
regex = re.compile(f"({'|'.join(map(re.escape, invalid_list))})\b")
s2 = [regex.sub('xyz', x) for x in s]
# ['123xyz', '456xye', '789xyf']
They advise using the re library here, however, I think it's easier, easier and better to use simple text.format() formatting
Code example:
list_of_words = ['text', 'be', 'there']
text = "This is an example {}. Normally there would {} something important here but {} isn't.".format(*list_of_words)
The output will look like this:
This is an example text. Normally there would be something important here but there isn't.
Try re.sub with custom function:
import re
lst = ["text", "be", "there"]
text = "This is an example [word]. Normally there would [word] something important here but [word] isn't."
text = re.sub(r"\[word\]", lambda _, i=iter(lst): next(i), text)
print(text)
Prints:
This is an example text. Normally there would be something important here but there isn't.
You can do that with a single call to sub:
big_regex = re.compile('|'.join(map(re.escape, prohibitedWords)))
the_message = big_regex.sub("repl-string", str(word[1]))
Example:
>>> import re
>>> prohibitedWords = ['Some', 'Random', 'Words']
>>> big_regex = re.compile('|'.join(map(re.escape, prohibitedWords)))
>>> the_message = big_regex.sub("<replaced>", 'this message contains Some really Random Words')
>>> the_message
'this message contains <replaced> really <replaced> <replaced>'
Note that using str.replace may lead to subtle bugs:
>>> words = ['random', 'words']
>>> text = 'a sample message with random words'
>>> for word in words:
... text = text.replace(word, 'swords')
...
>>> text
'a sample message with sswords swords'
while using re.sub gives the correct result:
>>> big_regex = re.compile('|'.join(map(re.escape, words)))
>>> big_regex.sub("swords", 'a sample message with random words')
'a sample message with swords swords'
As thg435 points out, if you want to replace words and not every substring you can add the word boundaries to the regex:
big_regex = re.compile(r'\b%s\b' % r'\b|\b'.join(map(re.escape, words)))
this would replace 'random' in 'random words' but not in 'pseudorandom words'.
try this:
prohibitedWords = ["MVGame","Kappa","DatSheffy","DansGame","BrainSlug","SwiftRage","Kreygasm","ArsonNoSexy","GingerPower","Poooound","TooSpicy"]
themessage = str(word[1])
for word in prohibitedwords:
themessage = themessage.replace(word, "(I'm an idiot)")
print themessage
Use a set for unique_words. Sets are considerably faster than lists for determining if an item is in them (see Python Sets vs Lists ).
Also, it's only a stylistic issue but I think you should drop the brackets in the if. It looks cleaner.
The code you have posted doesn't actually do any replacement. Here is a snippet that does:
for key,word in enumerate(data):
if word in unique_words:
data[key] = replacement
Here's a more compact way:
new_list = [replacement if word in unique_words else word for word in big_list]
I think unique_words is an odd name for the variable considering its use, perhaps it should be search_list?
Edit:
After your comment, perhaps this is better:
from collections import Counter
c = Counter(data)
only_once = [k for k,v in c.iteritems() if v == 1]
# Now replace all occurances of these words with something else
for k, v in enumerate(data):
if v in only_once:
data[k] = replacement
I'm trying to replace the same characters in a list of strings but nothing is happening?
list = ["stacy", "tracy", "kacy"]
newlist=[]
for x in list:
x.replace("cy","fi")
newlist.append(x)
print(newlist)What's wrong here?
Note that the condition if word in words in replacer performs a linear search on words if it's a list, as in the current code. Since this condition is executed for every word in the input, it would be good to optimize it a bit. You could for example pass a set of words instead of a list.
The names first_iter and second_iter are not very meaningful. It would be good to come up with some better names for these.
Regarding your question about the replacer function, you can shorten it a bit by using list comprehensions:
def replacer(title, words, randoms):
"""
:param title: string you want to split.
:param words: list of words you are looking to match.
:param randoms: list of random words to replace with words.
:return: new title
"""
return ' '.join([random.choice(randoms) if word in words else word
for word in title.split()])
From the docs:
The method
split()returns alistof all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num
More, there's this PEP8 thing which tells Python programmers how they can style their code according to some simple rules:
- for example, when writing docstrings you should use triple doubled-quotes