如何处理utf-8编码的String和BeautifulSoup?

时间:2010-10-29 17:56:10

标签: python beautifulsoup

如何使用正确的unicode替换unicode-Strings中的HTML实体?

u'"HAUS Kleider" - Über das Bekleiden und Entkleiden, das VerhŸllen und Veredeln'

u'"HAUS-Kleider" - Über das Bekleiden und Entkleiden, das Verhüllen und Veredeln'

修改
实际上这些实体是错误的。看起来好像是BeautifulSoup ...编辑它。

所以问题是:如何处理utf-8编码的String和BeautifulSoup?

from BeautifulSoup import BeautifulSoup

f = open('path_to_file','r')
lines = [i for i in f.readlines()]
soup = BeautifulSoup(''.join(lines))
allArticles = []
for row in rows:
    l =[]
    for r in row.findAll('td'):
            l += [r.string] # here things seem to go wrong
    allArticles+=[l]

Ü -> Ÿ代替Ü,但实际上我不希望无论如何都要更改编码。

>>> soup.originalEncoding
'utf-8'

但我无法生成一个正确的unicode字符串

3 个答案:

答案 0 :(得分:1)

我认为你需要的是ICU transliterators。我认为有一种方法可以 HTML实体音译成Unicode。

尝试符合您需要的音译器ID Hex/XML-Any。在演示页面上,您可以选择“插入样本:化合物”,然后在“化合物1”框中输入Hex/XML-Any,在框中添加一些输入数据并按“变换”。 this有帮助吗?

有一个Python ICU绑定,但我认为它没有得到很好的处理。

答案 1 :(得分:1)

htmlentitydefs.entitydefs["quot"]返回 '"'
这是一本将实体翻译成实际角色的字典。
从这一点开始,你应该能够轻松地继续下去。

答案 2 :(得分:0)

好吧,问题很愚蠢,我不得不承认。我正在交互式解释器中处理旧版rows。我不知道它的内容有什么问题,但这是正确的代码:

from BeautifulSoup import BeautifulSoup

f = open('path_to_file','r')
lines = [i for i in f.readlines()]
soup = BeautifulSoup(''.join(lines))
rows = soup.findAll('tr')
allArticles = []
for row in rows:
    l =[]
    for r in row.findAll('td'):
        l += [r.string]
    allArticles+=[l]
对我感到羞耻!