Python编码/解码问题

标签 python python-2.7 encoding ascii non-ascii-characters

如何将诸如“weren\xe2\x80\x99t”之类的字符串解码回正常编码。

所以这个词实际上不是“weren\xe2\x80\x99t”? 例如:

print "\xe2\x80\x9cThings"
string = "\xe2\x80\x9cThings"
print string.decode('utf-8')
print string.encode('ascii', 'ignore')

“Things
“Things
Things

但我其实想得到“东西。

或:

print "weren\xe2\x80\x99t"
string = "weren\xe2\x80\x99t"
print string.decode('utf-8')
print string.encode('ascii', 'ignore')

weren’t
weren’t
werent

但实际上我想得到的不是。

我应该怎么做?

最佳答案

我映射了最常见的奇怪字符,因此这是基于 Oliver W. 答案的非常完整的答案。

这个功能绝不是理想的,但它是最好的起点。 还有更多的字符定义:

http://utf8-chartable.de/unicode-utf8-table.pl?start=8192&number=128&utf8=string
http://www.utf8-chartable.de/unicode-utf8-table.pl?start=128&number=128&names=-&utf8=string-literal

...

def unicodetoascii(text):

    uni2ascii = {
            ord('\xe2\x80\x99'.decode('utf-8')): ord("'"),
            ord('\xe2\x80\x9c'.decode('utf-8')): ord('"'),
            ord('\xe2\x80\x9d'.decode('utf-8')): ord('"'),
            ord('\xe2\x80\x9e'.decode('utf-8')): ord('"'),
            ord('\xe2\x80\x9f'.decode('utf-8')): ord('"'),
            ord('\xc3\xa9'.decode('utf-8')): ord('e'),
            ord('\xe2\x80\x9c'.decode('utf-8')): ord('"'),
            ord('\xe2\x80\x93'.decode('utf-8')): ord('-'),
            ord('\xe2\x80\x92'.decode('utf-8')): ord('-'),
            ord('\xe2\x80\x94'.decode('utf-8')): ord('-'),
            ord('\xe2\x80\x94'.decode('utf-8')): ord('-'),
            ord('\xe2\x80\x98'.decode('utf-8')): ord("'"),
            ord('\xe2\x80\x9b'.decode('utf-8')): ord("'"),

            ord('\xe2\x80\x90'.decode('utf-8')): ord('-'),
            ord('\xe2\x80\x91'.decode('utf-8')): ord('-'),

            ord('\xe2\x80\xb2'.decode('utf-8')): ord("'"),
            ord('\xe2\x80\xb3'.decode('utf-8')): ord("'"),
            ord('\xe2\x80\xb4'.decode('utf-8')): ord("'"),
            ord('\xe2\x80\xb5'.decode('utf-8')): ord("'"),
            ord('\xe2\x80\xb6'.decode('utf-8')): ord("'"),
            ord('\xe2\x80\xb7'.decode('utf-8')): ord("'"),

            ord('\xe2\x81\xba'.decode('utf-8')): ord("+"),
            ord('\xe2\x81\xbb'.decode('utf-8')): ord("-"),
            ord('\xe2\x81\xbc'.decode('utf-8')): ord("="),
            ord('\xe2\x81\xbd'.decode('utf-8')): ord("("),
            ord('\xe2\x81\xbe'.decode('utf-8')): ord(")"),

                            }
    return text.decode('utf-8').translate(uni2ascii).encode('ascii')

print unicodetoascii("weren\xe2\x80\x99t")  

关于Python编码/解码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27996448/

相关文章:

python - 从 Django UserCreateForm 中删除 help_text

python - 如何在 Python 中创建新的自定义记录器函数

javascript atob 给出特殊字符串的错误

php - strftime 日期格式中的德语变音符号 - 正确的 utf-8 编码?

python - 如何在DataFrame中分离和添加值?

python - Jinja2 "recursive"标签实际上是如何工作的?

python - Neomodel 类定义

python - IO错误 : [Errno 2] No such file - Paramiko put()

python - 安装模块时无模块错误

python - 在 Delphi 中使用 MessagePack 序列化用户定义类型时可能出现编码问题?