Search code examples
pythonregexstringstring-matching

String to phrase replacement python


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.


Solution

  • I would suggest using a dict for your replacements:

    text = "Artificial intelligence is useful for us in every situation of deep learning."
    replacements = {"Artificial intelligence" : "Artificial_intelligence",
                    "deep learning" : "deep_learning"}
    

    Then your approach works (although it is case-sensitive):

    >>> for rep in replacements:
            text = text.replace(rep, replacements[rep])
    >>> print(text)
    Artificial_intelligence is useful for us in every situation of deep_learning.
    

    For other approaches (like the suggested regex-approach), have a look at SO: Python replace multiple strings.