Python Forum

Full Version: replace exact word
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Dear Python users,
I am trying to replace substrings in a pandas column with the respective exact substring. Imagine that I have the following text:
text = "I loves us. lovess"
and I would like to obtain
text = "I love usa. lovess"
I tried the following code:
import pandas as pd
text="i loves us. lovess"
df=pd.DataFrame([x.split(';') for x in text.split('\n')])
df['text'] = df[0].str.replace(r"loves","love", regex=True)
df['text'] = df['text'].str.replace(r"us","usa", regex=True)
However, the result from this code is "I love usa. loves". My original text has hundreds of typos, and I will need to replace several words. Any suggestion about how to improve this code would be appreciated. Thank you!
Make a dictionary over what you want to replace.
To replace exact word use word boundaries \bword\b,
see now that it replace loves but leave lovess alone.
import pandas as pd

text="i loves us. lovess test"
df = pd.DataFrame([x.split(';') for x in text.split('\n')])
replace_dict = {
    r"\bloves\b": "love",
    "us": "usa",
    "i": "I",
    "test": '999',
}

df_1 = df.replace({0: replace_dict}, regex=True)
Test.
>>> df
                         0
0  i loves us. lovess test
>>> df_1
                        0
0  I love usa. lovess 999