I'm trying to replace the occurrence of a word with another:
word_list = { "ugh" : "disappointed"}
tmp = ['laughing ugh']
for index, data in enumerate(tmp):
for key, value in word_list.iteritems():
if key in data:
tmp[index]=data.replace(key, word_list[key])
print tmp
Whereas this works... the occurrence of ugh
in laughing
is also being replaced in the output: ladisappointeding disappointed.
How does one avoid this so that the output is laughing disappointed
?
The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.
In that case, you may want to consider to replace word by word.
Example:
word_list = { "ugh" : "disappointed"}
tmp = ['laughing ugh']
for t in tmp:
words = t.split()
for i in range(len(words)):
if words[i] in word_list.keys():
words[i] = word_list[words[i]]
newline = " ".join(words)
print(newline)
Output:
laughing disappointed
Step-by-Step Explanations:
Get every sentence in the tmp list
:
for t in tmp:
split the sentence into words
:
words = t.split()
check whether any word
in words
are in the word_list
keys
. If it does, replace it with its value
:
for i in range(len(words)):
if words[i] in word_list.keys():
words[i] = word_list[words[i]]
rejoin the replaced words and print the result out:
newline = " ".join(words)
print(newline)
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