我正在尝试使用google.cloud.translate_v3将英语翻译成另一种语言


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笔记本。

方法是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,卢西亚诺。

相关内容

  • 没有找到相关文章

最新更新