Google 云翻译 API 客户端属性

Google Cloud Translate API client attribute

我正在尝试使用 Google 翻译 API。我已经按照他们的指南安装了所需的库并创建了一个虚拟环境。但是,当 运行 网站上提供的以下示例代码时,我不断收到有关库属性的错误消息:

"""Translates text into the target language.

Target must be an ISO 639-1 language code.
See https://g.co/cloud/translate/v2/translate-reference#supported_languages
"""
from google.cloud import translate_v2 as translate
translate_client = translate.Client()

if isinstance(text, six.binary_type):
    text = text.decode('utf-8')

# Text can also be a sequence of strings, in which case this method
# will return a sequence of results for each text.
result = translate_client.translate(
    text, target_language=target)

print(u'Text: {}'.format(result['input']))
print(u'Translation: {}'.format(result['translatedText']))
print(u'Detected source language: {}'.format(
    result['detectedSourceLanguage']))

输出:

    from google.cloud import translate_v2 as translate
  File "/Users/omar/Desktop/twilio/.venv/lib/python3.7/site-packa
ges/google/cloud/translate_v2/__init__.py", line 18, in <module>
    from pkg_resources import get_distribution
  File "/Users/omar/Desktop/twilio/.venv/lib/python3.7/site-packa
ges/pkg_resources/__init__.py", line 3191, in <module>
    @_call_aside
  File "/Users/omar/Desktop/twilio/.venv/lib/python3.7/site-packa
ges/pkg_resources/__init__.py", line 3175, in _call_aside
    f(*args, **kwargs)
  File "/Users/omar/Desktop/twilio/.venv/lib/python3.7/site-packages/pkg_resources/__init__.py", line 3219, in _initialize_master_working_set
    for dist in working_set
  File "/Users/omar/Desktop/twilio/.venv/lib/python3.7/site-packages/pkg_resources/__init__.py", line 3219, in <genexpr>
    for dist in working_set
  File "/Users/omar/Desktop/twilio/.venv/lib/python3.7/site-packages/pkg_resources/__init__.py", line 2726, in activate
    declare_namespace(pkg)
  File "/Users/omar/Desktop/twilio/.venv/lib/python3.7/site-packages/pkg_resources/__init__.py", line 2252, in declare_namespace
    _handle_ns(packageName, path_item)
  File "/Users/omar/Desktop/twilio/.venv/lib/python3.7/site-packages/pkg_resources/__init__.py", line 2185, in _handle_ns
    loader.load_module(packageName)
  File "/Users/omar/Desktop/twilio/google.py", line 7, in <module>
    translate_client = translate.Client()
AttributeError: module 'google.cloud.translate_v2' has no attribute 'Client'

为什么会出现此错误?

鉴于很长时间都没有答案,我将总结 Christopher 在评论中给出并由 Omar 测试的答案。如果帖子得到妥善解决以提高 post 的可见性,那么帖子应该有一个可接受的答案,以便其他遇到类似问题的用户可以更快地找到它。

问题的根本原因 AttributeError: module 'google.cloud.translate_v2' has no attribute 'Client' 是在环境本身中找到的。创建一个全新的虚拟环境并重新安装依赖项解决了这个问题。

这个问题可能有解决方案 here -- 我的意思是 pip install --upgrade google-cloud-translate。它对我有用