Skip to content
Advertisement

How to use googletrans’s Translator on SQLAlchemy object

I am trying to translate couple of columns in cloud MySQL table using googletrans‘s Translator function.

import pandas as pd
import googletrans
from googletrans import Translator
import sqlalchemy
import pymysql
import numpy as np
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine("mysql+pymysql:......")
Session = sessionmaker(bind = engine)
session = Session()
translator = Translator()

Here I read the MySQL table:

sql_stmt = "SELECT * FROM translate"
data = session.execute(sql_stmt)

And then here I try to translate it:

for to_translate in data:
    data.col1_Translated = translator.translate(to_translate.col1, dest = 'en')
    data.col2_Translated = translator.translate(to_translate.col2, dest = 'en')

But when I try to see if the translation took place using below code, I get no output.

for rows in data:
    print(rows.col1, rows.col1_Translated, rows.col2, rows.col2_Translated)

I am new to SQLALchemy and unable to find a solution. Could someone please let me know where I am going wrong and how to access the columns and apply the Translator function.

Advertisement

Answer

If I am not mistaken you want:

for to_translate in data:
    to_translate.col1_Translated = translator.translate(to_translate.col1, dest = 'en')
    # instead of:
    # data.col1_Translated = ...
    to_translate.col2_Translated = translator.translate(to_translate.col2, dest = 'en')

Right? You are assigning to data.col1_Translated so it gets overwritten each pass of the cycle.

If that’s not the problem, try:

for to_translate in data:
    print(translator.translate(to_translate.col1, dest = 'en'))
    print(translator.translate(to_translate.col2, dest = 'en'))

just to see if anything got translated. If it is, what do you want to do with the translation?

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement