首页 文章

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

提问于
浏览
1

如何用正确的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'

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

所以问题是: How to deal with utf-8 encoded String and 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

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

    尝试使用你想要的音译器id Hex/XML-Any . 在演示页面上,您可以选择"Insert Sample: Compound"然后在"Compound 1"框中输入 Hex/XML-Any ,在框中添加一些输入数据并按"transform" . this有帮助吗?

    有一个Python ICU绑定,但我认为它没有得到很好的照顾 .

  • 1

    htmlentitydefs.entitydefs["quot"] 返回 '"'
    这是一个将实体翻译成实际角色的字典 .
    从那时起你应该能够轻松地继续下去 .

  • 1

    好吧,问题很愚蠢,我不得不承认 . 我正在交互式解释器中使用旧版本的 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]
    

    对我感到羞耻!

相关问题