I am trying to translate couple of columns in cloud MySQL table using googletrans
‘s Translator
function.
JavaScript
x
14
14
1
import pandas as pd
2
import googletrans
3
from googletrans import Translator
4
import sqlalchemy
5
import pymysql
6
import numpy as np
7
from sqlalchemy import create_engine
8
from sqlalchemy.orm import sessionmaker
9
10
engine = create_engine("mysql+pymysql:......")
11
Session = sessionmaker(bind = engine)
12
session = Session()
13
translator = Translator()
14
Here I read the MySQL table:
JavaScript
1
3
1
sql_stmt = "SELECT * FROM translate"
2
data = session.execute(sql_stmt)
3
And then here I try to translate it:
JavaScript
1
4
1
for to_translate in data:
2
data.col1_Translated = translator.translate(to_translate.col1, dest = 'en')
3
data.col2_Translated = translator.translate(to_translate.col2, dest = 'en')
4
But when I try to see if the translation took place using below code, I get no output.
JavaScript
1
3
1
for rows in data:
2
print(rows.col1, rows.col1_Translated, rows.col2, rows.col2_Translated)
3
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:
JavaScript
1
6
1
for to_translate in data:
2
to_translate.col1_Translated = translator.translate(to_translate.col1, dest = 'en')
3
# instead of:
4
# data.col1_Translated = ...
5
to_translate.col2_Translated = translator.translate(to_translate.col2, dest = 'en')
6
Right? You are assigning to data.col1_Translated so it gets overwritten each pass of the cycle.
If that’s not the problem, try:
JavaScript
1
4
1
for to_translate in data:
2
print(translator.translate(to_translate.col1, dest = 'en'))
3
print(translator.translate(to_translate.col2, dest = 'en'))
4
just to see if anything got translated. If it is, what do you want to do with the translation?