再次编码

2024-03-28 16:20:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在python上使用sqlite:

from pysqlite2 import dbapi2 as sqlite
con = sqlite.connect('/home/argon/super.db')
cur = con.cursor()
cur.execute('select * from notes')
for i in cur.fetchall():
    print i[2]

我有时会得到这样的东西(我来自俄罗斯):

Ответ etc...

如果我把这个字符串传递给这个函数(它在其他项目中帮助了我):

def unescape(text):
    def fixup(m):
        text = m.group(0)
        if text[:2] == "&#":
            # character reference
            try:
                if text[:3] == "&#x":
                    return unichr(int(text[3:-1], 16))
                else:
                    return unichr(int(text[2:-1]))
            except ValueError:
                pass
        else:
            # named entity
            try:
                text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
            except KeyError:
                pass
        return text # leave as is
    return re.sub("&#?\w+;", fixup, text)

我得到了更奇怪的结果:

ÐÑвеÑиÑÑ Ñ ÑиÑиÑованием etc

我应该怎么做才能得到正常的西里尔符号?你知道吗


Tags: textfromsqlitereturnifdefasetc
1条回答
网友
1楼 · 发布于 2024-03-28 16:20:44

О看起来像是\xD0\x9E\u1054的UTF-8字节对。更广为人知的是西里尔字符О(大写O)。你知道吗

换句话说,你手上有奇怪的UTF-8编码数据。将{数字转换成字节(chr(208)就可以了),然后从UTF-8解码:

>>> (chr(208) + chr(158)).decode('utf-8')
u'\u1054'
>>> print (chr(208) + chr(158)).decode('utf-8')
О
>>> print (chr(208) + chr(158) + chr(209) + chr(130) + chr(208) + chr(178)).decode('utf-8')
Отв

相关问题 更多 >