【问题标题】:Having a hard time using the GCP translate API使用 GCP 翻译 API 时遇到困难
【发布时间】:2019-03-03 07:01:33
【问题描述】:

我正在用 Python 构建一个非常简单的程序。我想要的只是能够输入文本并获得另一种语言的翻译文本。

该程序将在不同的计算机上使用,API 密钥可以存储在代码中,因为我将是唯一使用它的人。

我不知道该怎么做,我已经搜索了几个小时没有任何进展。让它工作的最简单方法是什么?

编辑:到目前为止我有这个:

from google.cloud import translate

key = "...."
translate_client = translate.Client()
service = translate.build(developerKey=key)
service = build('translate', 'v2', developerKey=key)
translation = service.translate(['Detta är ett test'], target_language = 'en')
    print(translation)

【问题讨论】:

    标签: python google-cloud-platform cloud translate


    【解决方案1】:

    我已经通过使用另一种方法成功地做到了。我在Google Cloud Platform 中创建了一个服务帐户,并将凭据保存到json 文件中。然后,我为我的凭据设置了一个全局环境:

    import os
    from google.cloud import translate_v2 as translate
    
    # We setup the global variable for GCP service account credentials
    
    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'[path to your file].json'
    
    # We specify the path to the file we want to load
    
    filepath = r''
    
    # Instantiate the Google Translation API Client
    
    translate_client = translate.Client()
    
    output = []
    
    for chunk in chunker(elements, 100): #elements are the rows from an Excel 
        temp = translate_client.translate(
            chunk,
            target_language='fr'
        )
        output.extend(temp)
    

    【讨论】:

      【解决方案2】:

      此代码可能会对您有所帮助:

      #!/usr/bin/python
      
      from google.cloud import translate
      from apiclient.discovery import build
      key = 'YOUR API KEY'
      translate_client = translate.Client()
      service = build('translate', 'v2', developerKey=key)
      translation = service.translations().list(source='es',target='en',q=['Esto es un 
      texto traducido']).execute()
      print(translation)
      

      请参阅此 link 以获取 Translation API 方法 Python 参考文档。

      【讨论】:

      • 谢谢,虽然我收到了这个错误:“ModuleNotFoundError: No module named 'apiclient.discovery'” 我试过“pip install --upgrade google-api-python-client”但无济于事.
      • 你是用sudo执行的吗?例如sudo pip install --upgrade google-api-python-client
      • 我没有,使用 sudo 执行时出现错误。 “'sudo' 未被识别为内部或外部命令,..”
      • 你用的是windows机器吗?如果这是您的情况,请尝试运行 python -m pip install --upgrade google-api-python-client
      • 是的,我使用的是 Windows 机器。 {python} 给出“NameError: name 'python' is not defined. {py} 给我”Python 3.6.4 (v3......)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多