在Python中使用Google Cloud API翻译文本



我对编码很陌生,所以非常感谢您在这方面的帮助。我正在尝试用谷歌云翻译Python中的文本。我在Jupyter笔记本中使用了谷歌云的示例代码,但它没有打印任何翻译。它也没有显示任何错误。我做错了什么?

text = 'Text you wish to translate'
target_language = 'fr'
project_id = '[xxx]'
def sample_translate_text(text, target_language, project_id):
client = translate.TranslationServiceClient()
contents = [text]
parent = client.location_path(project_id, "global")
response = client.translate_text(
parent=parent,
contents=contents,
mime_type='text/plain',  
source_language_code='en-US',
target_language_code=target_language)
for translation in response.translations:
print(u"Translated text: {}".format(translation.translated_text))

您需要实际调用您定义的函数:

def sample_translate_text(text, target_language, project_id):
client = translate.TranslationServiceClient()
contents = [text]
parent = client.location_path(project_id, "global")
response = client.translate_text(
parent=parent,
contents=contents,
mime_type='text/plain',  
source_language_code='en-US',
target_language_code=target_language)
for translation in response.translations:
print(u"Translated text: {}".format(translation.translated_text))

import wikipedia as wiki
wiki.set_lang("pt")
text = wiki.page("Pandemia de COVID-19").content
target_language = 'fr'
project_id = '[xxx]'
sample_translate_text(text, target_language, project_id)

最新更新