gpt4 book ai didi

python - 如何使用 googletrans 在 Python 中翻译 Pandas 系列?

转载 作者:太空宇宙 更新时间:2023-11-04 08:32:34 24 4
gpt4 key购买 nike

我希望将 pandas 文本列从印度尼西亚语翻译成英语,并将此翻译文本添加为​​我的数据框中名为“英语”的新列。这是我的代码:

from googletrans import Translator

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

但是,我得到这个错误:

---------------------------------------------------------------------------
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

有谁知道我该如何解决这个问题?我有一只相当大的 Pandas df。

最佳答案

我猜你会得到这个错误,因为你将 pandas Series 对象传递给翻译函数( docs )而不是 str (字符串)目的。尝试使用 apply :

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

如果我在 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',))

它按预期工作。

关于python - 如何使用 googletrans 在 Python 中翻译 Pandas 系列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51664477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com