微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

来自 Googletrans 的 translate() 没有将文本翻译成英文

如何解决来自 Googletrans 的 translate() 没有将文本翻译成英文

我正在尝试将字段简短说明翻译成英文,因为有些行不是英文的。但是使用下面的代码我无法翻译。翻译列和原始列看起来完全一样。请参阅附加的输出图像。

from googletrans import Translator
translator = Translator()

mask = data['Short description'] !='en'

data['Short description_translated'] = data['Short description']
f = lambda x: translator.translate(x,dest='en').text
data.loc[mask,'Short description_translated'] = data.loc[mask,'Short description'].apply(f)
print (data)

Output

解决方法

您使用的 googletrans API 是与 translate.google.com 相同的服务。 Googletrans 不使用 official Google Translation API。它使用 Google Translate Ajax API。 您可以使用 Google 官方翻译 API 中提供的 Python 客户端库或 REST API。 可以参考下面提到的代码。

使用 Python 客户端库:

from os import environ

from google.cloud import translate

project_id = environ.get("PROJECT_ID","")
assert project_id
parent = f"projects/{project_id}"
client = translate.TranslationServiceClient()

sample_text = "Bonjour"
target_language_code = "en"

response = client.translate_text(
    contents=[sample_text],target_language_code=target_language_code,parent=parent,)

for translation in response.translations:
    print(translation.translated_text)

使用 REST API:

创建一个 request.json 文件并使用下面提到的 curl 命令。

请求.json

{
  "q": ["Bonjour","Merci"],"target": "en"
}

卷曲命令

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print- 
access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://translation.googleapis.com/language/translate/v2

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。