关于python:UnicodeEncodeError:’latin-1’编解码器不能编码字符

UnicodeEncodeError: 'latin-1' codec can't encode character

当我试图向数据库中插入一个外部字符时,可能是什么导致了这个错误?

1
>>UnicodeEncodeError: 'latin-1' codec can't encode character u'\u201c' in position 0: ordinal not in range(256)

我该如何解决?

谢谢!


我在使用python mysqldb模块时遇到了同样的问题。由于MySQL允许您在文本字段中存储所需的任何二进制数据,而不管字符集如何,我在这里找到了我的解决方案:

在python mysqldb中使用utf8

编辑:引用上述URL以满足第一条评论中的请求…

"UnicodeEncodeError:'latin-1' codec can't encode character ..."

This is because MySQLdb normally tries to encode everythin to latin-1.
This can be fixed by executing the following commands right after
you've etablished the connection:

1
2
3
4
db.set_character_set('utf8')
dbc.execute('SET NAMES utf8;')
dbc.execute('SET CHARACTER SET utf8;')
dbc.execute('SET character_set_connection=utf8;')

"db" is the result of MySQLdb.connect(), and"dbc" is the result of
db.cursor().


拉丁语1(ISO-8859-1)编码中不存在字符U+201C左双引号。

它出现在代码页1252(西欧)。这是一种基于ISO-8859-1的特定于Windows的编码,但它将额外的字符放在0x80-0x9f范围内。代码页1252经常与ISO-8859-1混淆,这是一种烦人的但现在却是标准的Web浏览器行为,如果您将页面作为ISO-8859-1提供服务,浏览器会将其视为CP1252。然而,它们实际上是两种不同的编码:

1
2
3
4
>>> u'He said \u201CHello\u201D'.encode('iso-8859-1')
UnicodeEncodeError
>>> u'He said \u201CHello\u201D'.encode('cp1252')
'He said \x93Hello\x94'

如果只将数据库用作字节存储,则可以使用CP1252对windows western代码页中的"和其他字符进行编码。但是,CP1252中没有的其他Unicode字符仍然会导致错误。

您可以使用encode(..., 'ignore')通过去掉字符来抑制错误,但实际上在本世纪,您应该在数据库和页面中使用utf-8。这种编码允许使用任何字符。您还应该理想地告诉MySQL您使用的是UTF-8字符串(通过在字符串列上设置数据库连接和排序规则),这样它就可以得到不区分大小写的比较和排序。


最好的解决办法是

  • 将mysql的charset设置为'utf-8'
  • 喜欢这个评论(加上use_unicode=Truecharset="utf8")


    db = MySQLdb.connect(host="localhost", user ="root", passwd ="", db ="testdb", use_unicode=True, charset="utf8") – KyungHoon Kim Mar
    13 '14 at 17:04

  • 详见:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    class Connection(_mysql.connection):

       """MySQL Database Connection Object"""

        default_cursor = cursors.Cursor

        def __init__(self, *args, **kwargs):
           """

            Create a connection to the database. It is strongly recommended
            that you only use keyword parameters. Consult the MySQL C API
            documentation for more information.

            host
              string, host to connect

            user
              string, user to connect as

            passwd
              string, password to use

            db
              string, database to use

            port
              integer, TCP/IP port to connect to

            unix_socket
              string, location of unix_socket to use

            conv
              conversion dictionary, see MySQLdb.converters

            connect_timeout
              number of seconds to wait before the connection attempt
              fails.

            compress
              if set, compression is enabled

            named_pipe
              if set, a named pipe is used to connect (Windows only)

            init_command
              command which is run once the connection is created

            read_default_file
              file from which default client values are read

            read_default_group
              configuration group to use from the default file

            cursorclass
              class object, used to create cursors (keyword only)

            use_unicode
              If True, text-like columns are returned as unicode objects
              using the connection's character set.  Otherwise, text-like
              columns are returned as strings.  columns are returned as
              normal strings. Unicode objects will always be encoded to
              the connection's character set regardless of this setting.

            charset
              If supplied, the connection character set will be changed
              to this character set (MySQL-4.1 and newer). This implies
              use_unicode=True.

            sql_mode
              If supplied, the session SQL mode will be changed to this
              setting (MySQL-4.1 and newer). For more details and legal
              values, see the MySQL documentation.

            client_flag
              integer, flags to use or 0
              (see MySQL docs or constants/CLIENTS.py)

            ssl
              dictionary or mapping, contains SSL connection parameters;
              see the MySQL documentation for more details
              (mysql_ssl_set()).  If this is set, and the client does not
              support SSL, NotSupportedError will be raised.

            local_infile
              integer, non-zero enables LOAD LOCAL INFILE; zero disables

            autocommit
              If False (default), autocommit is disabled.
              If True, autocommit is enabled.
              If None, autocommit isn't set and server default is used.

            There are a number of undocumented, non-standard methods. See the
            documentation for the MySQL C API for some hints on what they do.

           """


    我希望你的数据库至少是UTF-8。然后您需要运行yourstring.encode('utf-8'),然后再尝试将其放入数据库。


    您试图使用无法描述该代码点的编码ISO-8859-1 / Latin-1来存储Unicode代码点\u201c。您可能需要更改数据库以使用UTF-8,并使用适当的编码存储字符串数据,或者您可能希望在存储内容之前对输入进行消毒;例如,使用类似Sam Ruby的优秀i18n指南的方法。这就讨论了windows-1252可能引起的问题,并建议如何处理它,以及到示例代码的链接!


    sqlacalchemy用户可以简单地将其字段指定为convert_unicode=True

    例子:sqlalchemy.String(1000, convert_unicode=True)

    sqlacalchemy只接受unicode对象并返回它们,处理编码本身。

    文档


    使用以下代码段将文本从拉丁语转换为英语

    1
    2
    3
    4
    5
    6
    7
    import unicodedata
    def strip_accents(text):
        return"".join(char for char in
                       unicodedata.normalize('NFKD', text)
                       if unicodedata.category(char) != 'Mn')

    strip_accents('áéí?óúü')

    输出:

    'aeinouu'


    Latin-1(又称iso 8859-1)是一种单八位字符编码方案,不能将\u201c(")放入一个字节。

    你的意思是使用UTF-8编码吗?


    python:您需要添加#-*-编码:utf-8-*(去掉*周围的空格)到python文件的第一行。然后将以下内容添加到要编码的文本中:.encode("ascii","xmlcharrefreplace")。这将用它的ASCII等价物替换所有的Unicode字符。