【问题标题】:How to use an api key in python with google translation api如何通过谷歌翻译api在python中使用api键
【发布时间】:2017-11-06 19:52:51
【问题描述】:

我在谷歌文档中阅读了几个小时,但我仍然不知道我在做什么。 我基本上只是想使用谷歌翻译api来翻译我想到的几个单词。 我有一个包含帐单详细信息的有效帐户,我尝试了来自 google 的以下代码示例:


# Imports the Google Cloud client library
from google.cloud import translate

# Instantiates a client
translate_client = translate.Client()

# The text to translate
text = u'Hello, world!'
# The target language
target = 'ru'

# Translates some text into Russian
translation = translate_client.translate(
    text,
    target_language=target)

print(u'Text: {}'.format(text))
print(u'Translation: {}'.format(translation['translatedText']))

但它给了我这个错误:https://translation.googleapis.com/language/translate/v2?target=ru&q=Hello%2C+world%21 所以我不知道如何在 Python 中包含我的 API 密钥,谁能在这里给我一个快速的帮助,我的脑袋快炸了,我想我安装了很多我不需要的东西,比如谷歌云 SDK用于 Python 的 Shell 和 OAuth 库。 干杯

【问题讨论】:

    标签: python api sdk


    【解决方案1】:

    现在翻译客户端被调用:

    client = translate.TranslationServiceClient()
    

    您可以使用google的示例代码:

    from google.cloud import translate
    
    
    def translate_text(text="YOUR_TEXT_TO_TRANSLATE", project_id="YOUR_PROJECT_ID"):
        """Translating Text."""
    
        client = translate.TranslationServiceClient()
    
        parent = client.location_path(project_id, "global")
    
        # Detail on supported types can be found here:
        # https://cloud.google.com/translate/docs/supported-formats
        response = client.translate_text(
            parent=parent,
            contents=[text],
            mime_type="text/plain",  # mime types: text/plain, text/html
            source_language_code="en-US",
            target_language_code="fr",
        )
        # Display the translation for each input text provided
        for translation in response.translations:
            print(u"Translated text: {}".format(translation.translated_text))
    

    请记住将 project_id 更改为您的实际名称。

    【讨论】:

    • 如何通过api key使用?
    【解决方案2】:

    您需要设置一个环境变量 GOOGLE_APPLICATION_CREDENTIALS 并使用 api 密钥的 json 文件的路径,如此处所述https://cloud.google.com/translate/docs/setup?hl=en 或在您的代码中设置它https://cloud.google.com/docs/authentication/production#passing_code

    【讨论】:

      猜你喜欢
      • 2021-03-08
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      • 2010-11-11
      • 1970-01-01
      • 2010-10-10
      相关资源
      最近更新 更多