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

问题描述 投票:1回答:1

我是一个很新的编码,所以会感谢你的帮助。我正在尝试用Python与Google Cloud翻译文本。我在我的Jupyter笔记本中使用了Google Cloud的示例代码,但它没有打印任何翻译。它也没有显示任何错误。我做错了什么?

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))
python google-cloud-platform jupyter-notebook translation
1个回答
0
投票

你需要实际调用你定义的函数。

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)
© www.soinside.com 2019 - 2024. All rights reserved.