Home > OS >  python pandas translate text to english
python pandas translate text to english

Time:10-22

Hello I have a DataFrame from pandas that looks like this:

import pandas as pd
df = pd.DataFrame({"language": ["en", "it", "en", "it"],
                   "text": ["Hello", "Ciao", "This is english text", "Questo è un testo italiano"]})

I would like to translate all italian text to english. How can I do this?

CodePudding user response:

I agree that it is probably not a very good design like nbk has pointed out already. I've answered something similar here a few days ago which might be helpful.

To answer your question:

Using google translator, you can do:

from deep_translator import GoogleTranslator
gt = GoogleTranslator(source='it', target='en')
df.loc[df.language == 'it', 'text'] = df.loc[df.language == 'it', 'text'].apply(gt.translate)
  • Related