如何使用谷歌翻译 API 翻译抓取的文本

问题描述

我在 jupyter notebook 中使用美丽的汤从古腾堡计划中刮了一本书,并想将其翻译成另一种语言。但是,这样做有困难。

非常感谢您的帮助/建议;到目前为止,我的代码如下。翻译代码不起作用,并返回以下错误“WriteError: [Errno 32] broken pipe”

#Store url

url = 'https://www.gutenberg.org/files/514/514-h/514-h.htm'
html = r.text
print(html)
#Create a BeautifulSoup object from the HTML
soup = BeautifulSoup(html,"html5lib")
type(soup)

#get rid of non-text 

paragraph=soup.find_all("p")
for para in paragraph:
    print(para.text)

#translate text using Google Api translator
#init the Google Api translator

translator = Translator()
translation = translator.translate(text,dest="ar")
print(translation)

解决方法

translator.translate(text,dest="ar") 方法不返回字符串,而是返回一个实例。

试试下面的代码片段:

translation = translator.translate(text,dest="ar")
print(translation.text)

For more information.

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...