I have a text string and I want to replace two words with a single word. E.g. if the word is artificial intelligence
, I want to replace it with artificial_intelligence
. This needs to be done for a list of 200 words and on a text file of size 5 mb.
I tried string.replace
but it can work only for one element, not for the list.
Example
Text=’Artificial intelligence is useful for us in every situation of deep learning.’
List a : list b
Artificial intelligence: artificial_intelligence
Deep learning: deep_ learning
...
Text.replace('Artificial intelligence','Artificial_intelligence'
) is working.
But
For I in range(len(Lista)):
Text=Text.replace(Lista[I],List b[I])
doesn’t work.
2
Answers
I would suggest using a
dict
for your replacements:Then your approach works (although it is case-sensitive):
For other approaches (like the suggested regex-approach), have a look at SO: Python replace multiple strings.
Since you have a case problem between your list entries and your string, you could use the
re.sub()
function withIGNORECASE
flag to obtain what you want:Note the use of the
zip()
function wich allows to iterate over the two lists in the same time.Also note that Christian is right, a dict would be more suitable for your substitution data. The previous code would then be the following for the exact same result: