简体   繁体   中英

How to translate a Pandas Series in Python using googletrans?

I wish to translate a pandas column of text from Bahasa Indonesia to English, and add this translate text as a new column called 'English' in my data frame. Here is my code:

from googletrans import Translator

translator = Translator()
df['English'] = translator.translate(df['Review to Translate'], src='id', dest='en')

However, I get this error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-81-0fd41a244785> in <module>()
      2 
      3 translator = Translator()
----> 4 y['Review in English'] = translator.translate(y['Review to Translate'], src='id', dest='en')

~/anaconda3/lib/python3.6/site-packages/googletrans/client.py in translate(self, text, dest, src)
    170 
    171         origin = text
--> 172         data = self._translate(text, dest, src)
    173 
    174         # this code will be updated when the format is changed.

~/anaconda3/lib/python3.6/site-packages/googletrans/client.py in _translate(self, text, dest, src)
     73             text = text.decode('utf-8')
     74 
---> 75         token = self.token_acquirer.do(text)
     76         params = utils.build_params(query=text, src=src, dest=dest,
     77                                     token=token)

~/anaconda3/lib/python3.6/site-packages/googletrans/gtoken.py in do(self, text)
    179     def do(self, text):
    180         self._update()
--> 181         tk = self.acquire(text)
    182         return tk

~/anaconda3/lib/python3.6/site-packages/googletrans/gtoken.py in acquire(self, text)
    145         size = len(text)
    146         for i, char in enumerate(text):
--> 147             l = ord(char)
    148             # just append if l is less than 128(ascii: DEL)
    149             if l < 128:

TypeError: ord() expected a character, but string of length 516 found

Does anyone know how I can go about resolving this? I have a pretty large pandas df.

My guess would be you are getting this error because you are passing a pandas Series object to the translate function ( docs ) instead of a str (string) object. Try using apply :

from googletrans import Translator
translator = Translator()
df['English'] = df['Review to Translate'].apply(translator.translate, src='id', dest='en')

If I run this example at repl.it :

from googletrans import Translator
import pandas as pd
translator = Translator()
df = pd.DataFrame({'Spanish':['piso','cama']})
df['English'] = df['Spanish'].apply(translator.translate, src='es', dest='en').apply(getattr, args=('text',))

It works as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM