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

假如想象 提交于 2021-02-08 06:56:27

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/46116734/how-to-write-a-function-in-python-that-translates-each-row-of-a-csv-to-another-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!