python-3.x - “TranslationServiceClient”对象在 Google Cloud Translate 'location_path' 上没有属性 "translate_v3"

标签 python-3.x google-translate 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")
从昨天开始,更新了库后,我收到了这个错误:
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_pathlocation_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/

相关文章:

Python Curses - 检测退格键

python-3.x - python中的TMX(翻译内存交换)文件

java - Spring RestTemplate POST 与 Google Translate API

android - 谷歌云翻译 api 库未构建 - 发现重复类

translation - 强制 "vouvoiement"谷歌云翻译 API

windows - python “TypeError: getsockaddrarg: AF_INET address must be tuple, not int”中的socket()函数元组错误

python-3.x - 这个函数声明中 -> List[int] 是什么意思?

javascript - activeTab.url Safari 扩展

android - Google Translate API 出错(错误 :Execution failed for task ':app:transformClassesWithJarMergingForDebug, 重复条目)