我正在尝试使用 google.cloud.translate_v3 将英语翻译成其他语言

问题描述 投票:0回答:1
from google.cloud import translate_v3 as translate

def translate_sentence(sentence, target_language):
  # Create a TranslationClient
  client = translate.TranslationClient()

  # Translate the sentence
  translation = client.translate(sentence, target_language=target_language)

  # Return the translated sentence
  return translation['translatedText']



import pandas as pd

# Create a Pandas dataframe with a single sentence
df = pd.DataFrame({'sentence': ['This is a sentence to be translated.']})

# Translate the sentence to French
df['translated_sentence'] = df['sentence'].apply(lambda x: translate_sentence(x, 'fr'))

# Print the translated sentence
print(df['translated_sentence'][0])

我收到此错误

它还说凭据未知。所以我不能做凭证=凭证

AttributeError                            Traceback (most recent call last)
<ipython-input-11-f96ab99f032e> in <module>
      5 
      6 # Translate the sentence to French
----> 7 df['translated_sentence'] = df['sentence'].apply(lambda x: translate_sentence(x, 'fr'))
      8 
      9 # Print the translated sentence

5 frames
<ipython-input-10-ffde1fb2bc80> in translate_sentence(sentence, target_language)
      3 def translate_sentence(sentence, target_language):
      4   # Create a TranslationClient
----> 5   client = translate.TranslationClient()
      6 
      7   # Translate the sentence

AttributeError: module 'google.cloud.translate_v3' has no attribute 'TranslationClient'

我已经尝试过普通版本,但没有用。我正在使用 google colab 笔记本。

python client google-colaboratory google-translation-api google-cloud-translate
1个回答
0
投票

方法是

TranslationServiceClient()
,不是
TranslationClient()

我认为如果你将你的客户端实例化为:

from google.cloud import translate

client = translate.TranslationServiceClient()

这是来自 python 控制台的一个示例:

>>> from google.cloud import translate
>>> client = translate.TranslationServiceClient()
>>> client
<google.cloud.translate_v3.services.translation_service.client.TranslationServiceClient object at 0x7ff6db3905b0>

它将正常工作。

HTH, 卢西亚诺。

© www.soinside.com 2019 - 2024. All rights reserved.