我在谷歌文档中阅读了几个小时,但我仍然不知道我在做什么。 我基本上只是想使用谷歌翻译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密钥,任何人都可以在这里给我一个快速的帮助,我的头脑爆炸,我想我安装了很多我不需要的东西,比如说适用于Python的Google Cloud SDK Shell和OAuth库。 干杯
答案 0 :(得分:0)
翻译客户现在的呼叫方式是:
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 。
答案 1 :(得分:0)
您需要设置一个环境变量 GOOGLE_APPLICATION_CREDENTIALS 和 json 文件的路径,如此处说明的 api 密钥 https://cloud.google.com/translate/docs/setup?hl=en 或在您的代码中设置它 https://cloud.google.com/docs/authentication/production#passing_code