0

我正在尝试检测 beautifulsoup/python 中许多页面的语言。

这就是我如何使用美丽的汤来生成文本对象......

soup=BeautifulSoup(content,"html.parser")
text=soup.findAll('body')[-1].text

这会产生一个 unicode 对象,但是当我在其上运行 cld2 时经常会收到以下错误。

>>> cld2.detect(text)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 116: ordinal not in range(128)

如果我对其进行编码,我将不再收到该特定文本的错误。

>>> cld2.detect(text.encode('utf-8'))
(True, 4810, (('DUTCH', 'nl', 68, 845.0), ('ENGLISH', 'en', 31, 922.0), ('Unknown', 'un', 0, 0.0)))

...但我最终得到了另一段文字的不同错误

>>> cld2.detect(second_text)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1158-1161: ordinal not in range(128)
>>> cld2.detect(second_text.encode('utf-8'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
cld2.error: input contains invalid UTF-8 around byte 2079 (of 2605)

所有这些编码的东西完全让我感到困惑。有什么方法可以确保我只有有效的 utf-8 和 unicode 字符?

4

0 回答 0