0

I have a csv file with three columns, namely (cid,ccontent,value) . And I want to loop through each word in ccontent column and translate the words individually.

I found this code for translating a row but I want to translate each word not the row. How to write a function in Python that translates each row of a csv to another language?

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)

Thank you

testy
  • 11
  • 2
  • Hi testy, welcome to SO! As a general rule, the more reproducible your question is, the better. Ie if you could provide an example for the file you are reading in, that would make it easier for answerers to help you. – zabop Jul 27 '20 at 08:10

1 Answers1

0

You can try along the lines of, using list comprehension:

def translate_row(row):
    row0bywords = [translator.translate(eachword, dest='Fr') for eachword in row[0]]
    orw1bywords = [translator.translate(eachword, dest='Fr') for eachword in row[1]]
    return row0bywords, row1bywords
zabop
  • 3,885
  • 3
  • 14
  • 47