如何在 Python 中编写一个函数,将 csv 的每一行翻译成另一种语言?

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

如何在 Python 中编写一个函数,将 csv 文件的每一行翻译成另一种语言,并使用 pandas 将翻译作为另一列添加到同一 csv?我的输入文件如下所示:

我希望我的输出是这样的:

我是从这个开始的:

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'])

为了翻译单个句子,以下代码会有所帮助,但是您能帮我将它用作 csv 文件中所有行的函数吗?

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

谢谢。

类似的东西?

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)