For example:
list1 = ['mory','alphabet','fruit']
list2 = ['apple','banana','pear']
string = " There was a mory and the thing was a alphabet within the fruit. There were still fruit. But the banana was still there."
Now what I want to do is to change each appearance of a word from list1
with its equivalent in list2
. For example, "There was a mory" will be changed to "There was a apple".
I want to do this using for loops, however I cannot figure out how to run the list multiple times to change every part of the string.
CodePudding user response:
You can:
- create a dictionary mapping between the words to replace and their replacements using
zip()
- use
.split()
to get the words in the original text (splitting into individual sentences, then into individual words), and - iterate over those words and find their replacements (if they exist):
list1 = ['mory','alphabet','fruit']
list2 = ['apple','banana','pear']
words_to_replace = {to_replace: replacement for to_replace, replacement in zip(list1, list2)}
string = ("There was a mory and the thing was a alphabet within the fruit. "
"There were still fruit. But the banana was still there.")
sentences = string.split('. ')
original_words = [sentence.split(' ') for sentence in sentences]
result_sentences = []
for sentence in sentences:
replacement_sentence_words = []
for word in sentence.split(' '):
if word in words_to_replace:
replacement_sentence_words.append(words_to_replace[word])
else:
replacement_sentence_words.append(word)
result_sentences.append(' '.join(replacement_sentence_words))
result = '. '.join(result_sentences)
print(result)
This prints:
There was a apple and the thing was a banana within the pear. There were still pear. But the banana was still there.
As an aside, you shouldn't use repeated .replace()
for this task. Consider the following:
list1 = ['mory','apple']
list2 = ['apple','banana']
data = 'mory apple'
for word, replacement in zip(list1, list2):
data = data.replace(word, replacement)
print(data)
This will output banana banana
, even though mory
is mapped to apple
.
CodePudding user response:
There are 3 ways to solve your problem
The most basic way:
list1 = ['mory','alphabet','fruit']
list2 = ['apple','banana','pear']
string = "There was a mory and the thing was a alphabet within the fruit. "
for i in range(len(list1)):
string = string.replace(list1[i], list2[i]
Here, i am just using for loop
in range of lenth of list1, and replacing the index i of list1 to index i of list2.
Using dictionary
list1 = ['mory','alphabet','fruit']
list2 = ['apple','banana','pear']
string = "There was a mory and the thing was a alphabet within the fruit. "
List_dict= {j:list2[i] for i,j in enumerate(list1)}
for i in list1:
string=string.replace(i, List_dict.get(i)
We have just read the elements of list1 and used enumerate
function to the index. Then we have used a dict
to associate element of list1 to element of list2. After that, we have used .replace
function to replace value of list1 to value of list2.
Using list:
list1 = ['mory','alphabet','fruit']
list2 = ['apple','banana','pear']
string = "There was a mory and the thing was a alphabet within the fruit. "
List_3= [j, list2[i] for i,j in enumerate (lists)]
for i in List_3:
String=string.replace(i[0],i[1])
The same consepts of dictionary method goes here, the difference is in first method we are using dictionary comprehension, you can use normal for loop
too to achieve it.
There are many more way to solve this problem, but the methods i have mentioned are the main or basic ones.
CodePudding user response:
You can try this, I compiled from some resource. And the resource I put on below as reference.
list1 = ['mory','alphabet','fruit']
list2 = ['apple','banana','pear']
string = "There was a mory and the thing was a alphabet within the fruit. There were still fruit. But the banana was still there."
for i in range(len(list1)):
string = string.replace(list1[i], list2[i])
# Output
# There was a apple and the thing was a banana within the pear. There were still pear. But the banana was still there.
Reference :
CodePudding user response:
I think this succinct code solves the problem:
string = " There was a mory and the thing was a alphabet within the fruit. There were still fruit. But the banana was still there."
list1 = ['mory','alphabet','fruit']
list2 = ['apple','banana','pear']
for i in range(len(list1)):
while string.find(list1[i]) != -1:
index = string.find(list1[i])
string = string[:index] list2[i] string[(index len(list1[i])):]
print(string)
Output:
There was a apple and the thing was a banana within the pear. There were still pear. But the banana was still there.
How this code works is that for every value in list1
, while that element exists inside string
, we replace it with its corresponding value in list2
.
However, if you want to use a built in function to replace easier, you can just use:
for i in range(len(list1)):
string = string.replace(list1[i],list2[i])
I hope this helped! Let me know if you need any other clarification or details :)
CodePudding user response:
Try this:
from functools import reduce
original_values = ["mory", "alphabet", "fruit"]
updated_values = ["apple", "banana", "pear"]
original_sentence = "There was a mory and the thing was a alphabet within the fruit. There were still fruit. But the banana was still there."
updated_sentence = reduce(lambda x, y: x.replace(y[0], y[1]), zip(original_values, updated_values), original_sentence)
print(updated_sentence)
Docs for functools.reduce: https://docs.python.org/3/library/functools.html#functools.reduce
Docs for str.replace: https://docs.python.org/3/library/stdtypes.html#str.replace