1

I'm trying to write a code that checks the sentences in a csv file and search for the words that are given from a second csv file and replace them,my code is as bellow it doesn't return any errors but it is not replacing any words for some reasons and printing back the same sentences without and replacement.


import string
import pandas as pd
text=pd.read_csv("sentences.csv")
change=pd.read_csv("replace.csv")
for row in text:
    print(text.replace(change['word'],change['replacement']))

the sentences csv file looks like

enter image description here

and the change csv file looks like

enter image description here

programming freak
  • 859
  • 5
  • 14
  • 34
  • Does this answer your question? [Use dictionary to replace a string within a string in Pandas columns](https://stackoverflow.com/questions/46342492/use-dictionary-to-replace-a-string-within-a-string-in-pandas-columns) – rpanai Dec 24 '19 at 12:59
  • not that similar wasn't able to follow it sorry – programming freak Dec 24 '19 at 13:16

3 Answers3

3

Try:

text=pd.read_csv("sentences.csv")
change=pd.read_csv("replace.csv")
toupdate = dict(zip(change.word, change.replacement))
text = text['sentences'].replace(toupdate, regex=True)
print(text)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

dataframe.replace(x,y) changes complete x to y, not part of x.

you have to use regex or custom function to do what you want. for example :

change_dict = dict(zip(change.word,change.replacement))
def replace_word(txt):
    for key,val in change_dict.items():
        txt = txt.replace(key,val)
return txt
print(text['sentences'].apply(replace_word))
cerofrais
  • 1,117
  • 1
  • 12
  • 32
0

// to create one more additonal column to avoid any change in original colum

text["new_sentence"]=text["sentences"]

for changeInd in change.index:
    for eachTextid in text.index:
        text["new_sentence"][eachTextid]=text["new_sentence"][eachTextid].replace(change['word'][changeInd],change['replacement'][changeInd])

clear code: click here plz

julka
  • 1,172
  • 2
  • 13
  • 29