我正在使用 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")
从昨天开始,更新了库后,我收到了这个错误:AttributeError: 'TranslationServiceClient' object has no attribute 'location_path'
是不是这些库变了?引导此查询的正确方法是什么?
最佳答案
也遇到了这个。并非所有文档都已更新,但他们发布了迁移指南:
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}"
并更改 client.location_path
至 location_path
如果这是您在许多地方使用的东西。还有更多彻底的变化。他们现在更喜欢你传递一个名为
request
的字典。到 API 方法,虽然旧的方式仍然被接受。因此,您的代码可能如下所示: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],
}
)
现在,您很可能会问“我怎么知道在那个请求字典中放什么?”。看起来该库附带了适用于每种方法的字典的类型注释:https://googleapis.dev/python/translation/latest/translate_v3/types.html例如,我在您对另一个答案的评论中读到您在使用
detect_language
时遇到了问题。方法。方法签名表明如果使用关键字参数,content
应该是一个有效的,所以我不知道为什么会失败 - 也许这是一个错误。但是,如果您使用
request
字典,应该看起来 like this .您会看到这些键似乎与方法签名关键字并不完全对应(尽管 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
(如您所见,返回类型有些复杂)
关于python-3.x - “TranslationServiceClient”对象在 Google Cloud Translate 'location_path' 上没有属性 "translate_v3",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63303992/