5

我知道关于这个问题有很多线程,但我还没有找到一个可以解决我的问题的线程。

我正在尝试打印一个字符串,但打印时它不显示特殊字符(例如æ、ø、å、ö 和 ü)。当我使用它打印字符串时repr(),我得到:

u'Von D\xc3\xbc'u'\xc3\x96berg'

有谁知道我如何将其转换为Von Düand Öberg?对我来说重要的是这些字符不会被忽略,例如myStr.encode("ascii", "ignore").

编辑

这是我使用的代码。我使用 BeautifulSoup 来抓取网站。<td>表格 ( ) 中单元格 ( ) 的内容<table>被放入变量name。这是包含我无法打印的特殊字符的变量。

web = urllib2.urlopen(url);
soup = BeautifulSoup(web)
tables = soup.find_all("table")
scene_tables = [2, 3, 6, 7, 10]
scene_index = 0
# Iterate over the <table>s we want to work with
for scene_table in scene_tables:
    i = 0
    # Iterate over < td> to find time and name
    for td in tables[scene_table].find_all("td"):
        if i % 2 == 0:  # td contains the time
            time = remove_whitespace(td.get_text())
        else:           # td contains the name
            name = remove_whitespace(td.get_text()) # This is the variable containing "nonsense"
            print "%s: %s" % (time, name,)
        i += 1
    scene_index += 1
4

3 回答 3

12

预防胜于治疗。您需要了解这些垃圾是如何产生的。请编辑您的问题以显示创建它的代码,然后我们可以帮助您修复它。好像有人做过:

your_unicode_string =  original_utf8_encoded_bytestring.decode('latin1')

解决方法是简单地反转该过程,然后进行解码。

correct_unicode_string = your_unicode_string.encode('latin1').decode('utf8')

更新根据您提供的代码,可能的原因是网站声明它是用ISO-8859-1(aka latin1) 编码的,但实际上它是用 UTF-8 编码的。请更新您的问题以向我们显示网址。

如果不能显示,请阅读BS 文档;看起来您需要使用:

BeautifulSoup(web, from_encoding='utf8')
于 2012-04-02T10:11:34.783 回答
3

许多语言的 Unicode 支持令人困惑,因此您的错误是可以理解的。u这些字符串是 UTF-8 字节,如果您将放在前面,它将正常工作:

>>> err = u'\xc3\x96berg'
>>> print err
Ã?berg
>>> x = '\xc3\x96berg'
>>> print x
Öberg
>>> u = x.decode('utf-8')
>>> u
u'\xd6berg'
>>> print u
Öberg

更多信息:

http://www.joelonsoftware.com/articles/Unicode.html

http://docs.python.org/howto/unicode.html


在继续之前,您真的应该真正阅读这些链接并了解发生了什么。但是,如果您绝对需要今天可以使用的东西,您可以使用我不好意思公开发布的这个可怕的黑客:

def convert_fake_unicode_to_real_unicode(string):
    return ''.join(map(chr, map(ord, string))).decode('utf-8')
于 2012-04-02T09:25:58.780 回答
1

字符串的内容不是 unicode,它们是 UTF-8 编码的。

>>> print u'Von D\xc3\xbc'
Von Dü
>>> print 'Von D\xc3\xbc'
Von Dü

>>> print unicode('Von D\xc3\xbc', 'utf-8')
Von Dü
>>> 

编辑:

>>> print '\xc3\x96berg' # no unicode identifier, works as expected because it's an UTF-8 encoded string
Öberg
>>> print u'\xc3\x96berg' # has unicode identifier, means print uses the unicode charset now, outputs weird stuff
Ãberg

# Look at the differing object types:
>>> type('\xc3\x96berg')
<type 'str'>
>>> type(u'\xc3\x96berg')
<type 'unicode'>

>>> '\xc3\x96berg'.decode('utf-8') # this command converts from UTF-8 to unicode, look at the unicode identifier in the output
u'\xd6berg'
>>> unicode('\xc3\x96berg', 'utf-8') # this does the same thing
u'\xd6berg'
>>> unicode(u'foo bar', 'utf-8') # trying to convert a unicode string to unicode will fail as expected
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: decoding Unicode is not supported
于 2012-04-02T09:27:34.943 回答