There isn’t any common way to replace a list of strings with another list of strings within a text without applying a for loop or multiple regular expression calls.
With this quick and easy hack, we can do it in one line of code using Pandas DataFrames.
import pandas as pd df = pd.DataFrame({'text': ['Billy is going to visit Rome in November', 'I was born in 10/10/2010', 'I will be there at 20:00']}) print(df)
text
0 Billy is going to visit Rome in November
1 I was born in 10/10/2010
2 I will be there at 20:00
to_replace=['Billy','Rome','January|February|March|April|May|June|July|August|September|October|November|December', '\d{2}:\d{2}', '\d{2}/\d{2}/\d{4}'] replace_with=['name','city','month','time', 'date'] print(df.text.replace(to_replace, replace_with, regex=True))
0 name is going to visit city in month
1 I was born in date
2 I will be there at time
Here you can find a great example of this hack where we’re replacing all the punctuation marks. Notice that the replacements on the text are done with the order they appear in the lists .