Search code examples
pythonexcelattributeerrorgoogle-translate

Importing Excel and Translation then Exporting Excel again


I'd like to translate with a goolge translator from excel file and then export to excel again. But I got an error :

AttributeError: 'str' object has no attribute 'to_excel'
import pandas as pd
from google_trans_new import google_translator

df = pd.read_excel("data.xlsx")
print(df)

translator = google_translator()
translate_text = translator.translate(df,lang_tgt='fr')
print(translate_text)

translate_text.to_excel('new_data.xlsx')

below is printed result

      Hi
0  Hello

salut  0 bonjour

data.xlsx is like this

enter image description here


Solution

  • You can try following code:

    import pandas as pd
    from google_trans_new import google_translator
    
    text = ','.join(pd.read_excel('demo.xlsx',header=None)[0].values)
    translated_text = translator.translate(text,lang_tgt='fr')
    pd.DataFrame(translated_text.split(',')).to_excel('new_data.xlsx',header=False,index=False)
    

    The above code does following 3 steps:

    1. Read the values from a excel file & make it a string of words with comma separators.
    2. Pass that string to the translator.
    3. Translated text is again splitted on comma and converted to a dataframe to store it in a excel file.