Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
replace exact word
#1
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!
Reply
#2
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Replace a text/word in docx file using Python Devan 4 3,471 Oct-17-2023, 06:03 PM
Last Post: Devan
Question in this code, I input Key_word, it can not find although all data was exact Help me! duchien04x4 3 1,057 Aug-31-2023, 05:36 PM
Last Post: deanhystad
  Working with Excel and Word, Several Questions Regarding Find and Replace Brandon_Pickert 4 1,570 Feb-11-2023, 03:59 PM
Last Post: Brandon_Pickert
  python-docx regex: replace any word in docx text Tmagpy 4 2,252 Jun-18-2022, 09:12 AM
Last Post: Tmagpy
  Matching Exact String(s) Extra 4 1,933 Jan-12-2022, 04:06 PM
Last Post: Extra
Question Problem: Check if a list contains a word and then continue with the next word Mangono 2 2,518 Aug-12-2021, 04:25 PM
Last Post: palladium
  Assistance with running a few lines of code at an EXACT time nethatar 5 3,272 Feb-24-2021, 10:43 PM
Last Post: nilamo
  Exact Match Kristenl2784 2 2,850 Jul-26-2020, 03:29 PM
Last Post: Kristenl2784
  Two exact "Fors" giving me different results? FilGonca 2 2,023 May-04-2020, 12:36 PM
Last Post: FilGonca
  Python Speech recognition, word by word AceScottie 6 16,028 Apr-12-2020, 09:50 AM
Last Post: vinayakdhage

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020