Search code examples
pythonpandasdataframetextdeep-learning

How to replace specific string in data frame column value?


I have input.txt file that has 2 columns (file_name,text) and want to replace " " seprater charchter (which represnt tab here becuse I spreated txt file by this char) that apperar in text column

example for input file :

0.jpg   Jól olvasom?   Összesen négy, azaz 4   számot játszott   el 
1.jpg   a csapat a   koncerten  Ilyet még nem is hallottam 

I wrote the following code :

df = pd.read_csv(f'{path}labels.txt',# labels labels_tab_remove
                 header=None,
                 delimiter='   ',
                 encoding="utf8",
                 engine='python'
                 )
df.rename(columns={0: "file_name", 1: "text"}, inplace=True)
print(df.head())

So I want to replace " " tab by " " single space

for idx in range(len(df)):
 df['text'][idx].replace("   "," ")

So the expacted output :

0.jpg   Jól olvasom? Összesen négy, azaz 4 számot játszott el 
1.jpg   a csapat a koncerten Ilyet még nem is hallottam

Solution

  • Do you really need Pandas to do that?

    import re
    
    with (open('labels.txt', encoding='utf-8') as fp1,
          open('labels_clean.txt', mode='w', encoding='utf-8') as fp2):
        for row in fp1:
            if row.strip():
                file_text, text = re.split(r'\s{3}', row, maxsplit=1)
                text = re.sub(r'\s+', ' ', text)
                fp2.write(f"{file_text}{' ':4}{text}\n")
    

    Content of labels_clean.txt:

    0.jpg    Jól olvasom? Összesen négy, azaz 4 számot játszott el 
    1.jpg    a csapat a koncerten Ilyet még nem is hallottam