您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python编码utf-8

python编码utf-8

您不需要对 已经 编码的数据进行编码。当您尝试执行此操作时,Python会先尝试对其进行 解码unicode然后再将其编码回UTF-8。这就是这里失败的原因:

    >>> data = u'\u00c3'            # Unicode data
    >>> data = data.encode('utf8')  # encoded to UTF-8
    >>> data
    '\xc3\x83'
    >>> data.encode('utf8')         # Try to *re*-encode it
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

只需直接写您的数据文件,也 没有 必要编码已编码的数据。

如果改为建立unicode值,则实际上必须将那些值编码为可写入文件。您想使用codecs.open()它,它返回一个文件对象,该文件对象将为您将Unicode值编码为UTF-8。

您也 确实 不想写UTF-8 BOM, 除非必须 支持否则无法读取UTF-8的Microsoft工具(例如MS Notepad)。

对于您的MysqL插入问题,您需要做两件事:

添加charset='utf8'到您的MysqLdb.connect()通话中。

使用unicode对象,而不是str查询或插入对象,而是 使用sql参数, 以便MysqL连接器可以为您做正确的事情:

artiste = artiste.decode('utf8')  # it is already UTF8, decode to unicode

c.execute(‘SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s’, (artiste,))

c.execute(‘INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)’, (artiste, artiste + u’/’))

如果您codecs.open()改为自动解码内容,则实际上可能会更好:

    import codecs

    sql = mdb.connect('localhost','admin','ugo&(-@F','music_vibration', charset='utf8')

    with codecs.open('config/index/'+index, 'r', 'utf8') as findex:
        for line in findex:
            if u'#artiste' not in line:
                continue

            artiste=line.split(u'[:::]')[1].strip()

        cursor = sql.cursor()
        cursor.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
        if not cursor.fetchone()[0]:
            cursor = sql.cursor()
            cursor.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
            artists_inserted += 1

您可能需要复习Unicode和UTF-8和编码。我可以推荐以下文章

Python的Unicode指南

Ned Batchelder的实用Unicode

每个软件开发人员绝对,肯定必须绝对了解Unicode和字符集(无借口!)作者:Joel Spolsky

python 2022/1/1 18:41:43 有269人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶