我使用的是Python3.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'是不是这些库发生了变化?引导这一调查的正确方式是什么?
发布于 2020-08-14 18:39:34
也遇到了这个问题。并非所有文档都已更新,但他们已经发布了迁移指南:
https://googleapis.dev/python/translation/latest/UPGRADING.html
您可以用"projects/<PROJECT_ID>/locations/<LOCATION>"替换parent
或定义
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(正如您所看到的,返回类型有点复杂)
发布于 2020-08-08 01:49:01
我也有同样的问题。我去掉了所有的“父”代码,并将其添加到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')文档:https://googleapis.dev/python/translation/latest/translate_v3/services.html
https://stackoverflow.com/questions/63303992
复制相似问题