Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a function in Python that translates each row of a csv to another language?

How to write a function in Python that translates each row of a csv file to another language and adds the translation as another column to the same csv using pandas? The input file I have, looks like this:

enter image description here

and I would like my output to be like:

enter image description here

I started with this:

from googletrans import Translator
import pandas as pd

data = pd.read_csv('~/file/my_file.csv')[['A','B']]
df = pd.DataFrame(data, columns=['A','B','A_translation', 'B_translation'])

and for translating a single sentence the following code helps, but could you please help me to use it as a function for all rows in a csv file?

sentence = 'The quick brown fox'
translations = translator.translate(sentence, dest = 'Fr')
for translation in translations:
     tr = translation.text 
     org = translation.origin

Thanks.

like image 631
hets Avatar asked Oct 26 '25 14:10

hets


1 Answers

Something like that ?

from googletrans import Translator
import pandas as pd

headers = ['A','B','A_translation', 'B_translation']
data = pd.read_csv('./data.csv')
translator = Translator()
# Init empty dataframe with much rows as `data`
df = pd.DataFrame(index=range(0,len(data)), columns=headers)


def translate_row(row):
    ''' Translate elements A and B within `row`. '''
    a = translator.translate(row[0], dest='Fr')
    b = translator.translate(row[1], dest='Fr')
    return pd.Series([a.origin, b.origin, a.text, b.text], headers)


for i, row in enumerate(data.values):
    # Fill empty dataframe with given serie.
    df.loc[i] = translate_row(row)

print(df)
like image 195
Arount Avatar answered Oct 29 '25 03:10

Arount



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!