Rim*_*imo 6 google-translate python-3.x google-cloud-translate
我正在使用 Python 3.6 和 google-cloud-translate 包。
from google.cloud import translate_v3 as translate
client = translate.TranslationServiceClient(credentials = credentials)
parent = client.location_path("my-location", "global")
Run Code Online (Sandbox Code Playgroud)
从昨天开始,更新了库后,我收到了这个错误:
AttributeError: 'TranslationServiceClient' object has no attribute 'location_path'
Run Code Online (Sandbox Code Playgroud)
是不是这些库变了?引导此查询的正确方法是什么?
也遇到了这个。并非所有文档都已更新,但他们发布了迁移指南:
https://googleapis.dev/python/translation/latest/UPGRADING.html
你可以parent用"projects/<PROJECT_ID>/locations/<LOCATION>"
或定义
def location_path(project_id, location):
# might as well use an f-string, the new library supports python >=3.6
return f"projects/{project_id}/locations/{location}"
Run Code Online (Sandbox Code Playgroud)
如果这是您在许多地方使用的东西,请更改client.location_path为location_path。
还有更多彻底的变化。他们现在更喜欢你传递一个调用requestAPI 方法的字典,尽管旧的方法仍然被接受。因此,您的代码可能如下所示:
from google.cloud import translate_v3 as translate
client = translate.TranslationServiceClient(credentials=credentials)
response = client.translate_text(
request={
"parent": "projects/my-location/locations/global",
"target_language_code": target_language_code,
"contents": [text],
}
)
Run Code Online (Sandbox Code Playgroud)
现在,您很可能会问“我怎么知道在那个请求字典中放什么?”。看起来该库带有适用于每种方法的字典的类型注释:https : //googleapis.dev/python/translation/latest/translate_v3/types.html
例如,我在您对另一个答案的评论中读到您在使用该detect_language方法时遇到了问题。方法签名表明如果你使用关键字参数,content应该是一个有效的,所以我不知道为什么会失败——也许这是一个错误。
但是,如果您使用request字典,则应如下所示。您会看到这些键似乎与方法签名关键字并不完全对应(尽管content是其中之一)。
这段代码可以工作:
response = client.detect_language({
"parent": "projects/my-location/locations/global",
"content": "Tá Gaeilge Agam, ach tá mé i mo chonai i Sasana",
})
lang = response.languages[0].language_code
Run Code Online (Sandbox Code Playgroud)
(如您所见,返回类型有些复杂)
小智 0
我也有同样的问题。我一起摆脱了“父”代码,并将其添加到 translate_text 方法中。
client = translate.TranslationServiceClient()
response = client.translate_text(
parent = 'projects/{}'.format(project_id),
contents = [text],
mime_type = 'text/plain',
source_language_code = 'en-US',
target_language_code = 'es')
Run Code Online (Sandbox Code Playgroud)
文档: https ://googleapis.dev/python/translation/latest/translate_v3/services.html
| 归档时间: |
|
| 查看次数: |
1587 次 |
| 最近记录: |