Programing

UnicodeEncodeError : 'latin-1'코덱은 문자를 인코딩 할 수 없습니다.

lottogame 2020. 10. 7. 07:14
반응형

UnicodeEncodeError : 'latin-1'코덱은 문자를 인코딩 할 수 없습니다.


데이터베이스에 외래 문자를 삽입하려고 할 때이 오류의 원인은 무엇입니까?

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

그리고 어떻게 해결합니까?

감사!


문자 U + 201C 왼쪽 큰 따옴표는 Latin-1 (ISO-8859-1) 인코딩에 없습니다.

그것은 이다 코드 페이지 1252 (서유럽)에 존재. 이것은 ISO-8859-1을 기반으로하지만 0x80-0x9F 범위에 추가 문자를 넣는 Windows 관련 인코딩입니다. 코드 페이지 1252는 ISO-8859-1과 혼동되는 경우가 많으며, 페이지를 ISO-8859-1로 제공하면 브라우저가 대신 cp1252로 처리하는 성가 시지만 이제는 표준 웹 브라우저 동작입니다. 그러나 실제로는 두 가지 고유 한 인코딩입니다.

>>> 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에없는 다른 유니 코드 문자는 오류를 발생시킵니다.

encode(..., 'ignore')문자를 제거하여 오류를 억제하는 데 사용할 수 있지만 실제로 이번 세기에는 데이터베이스와 페이지 모두에서 UTF-8을 사용해야합니다. 이 인코딩을 사용하면 모든 문자를 사용할 수 있습니다. 또한 이상적으로 MySQL에 UTF-8 문자열을 사용하고 있다고 알려 주어야합니다 (데이터베이스 연결 및 문자열 열에 대한 데이터 정렬을 설정하여). 그러면 대소 문자를 구분하지 않는 비교 및 ​​정렬을 올바르게 수행 할 수 있습니다.


Python MySQLdb 모듈을 사용할 때 이와 동일한 문제가 발생했습니다. MySQL을 사용하면 문자 집합에 관계없이 텍스트 필드에 원하는 거의 모든 이진 데이터를 저장할 수 있으므로 여기에서 해결책을 찾았습니다.

Python MySQLdb에서 UTF8 사용

편집 : 첫 번째 댓글의 요청을 충족하기 위해 위 URL에서 인용 ...

"UnicodeEncodeError : 'latin-1'코덱이 문자를 인코딩 할 수 없습니다 ..."

이는 MySQLdb가 일반적으로 모든 것을 latin-1로 인코딩하려고하기 때문입니다. 연결을 해제 한 후 바로 다음 명령을 실행하여이 문제를 해결할 수 있습니다.

db.set_character_set('utf8')
dbc.execute('SET NAMES utf8;')
dbc.execute('SET CHARACTER SET utf8;')
dbc.execute('SET character_set_connection=utf8;')

"db"는의 결과 MySQLdb.connect()이고 "dbc"는의 결과입니다 db.cursor().


가장 좋은 해결책은

  1. mysql의 문자 세트를 'utf-8'로 설정하십시오.
  2. 이 주석을 좋아하십시오 (추가 use_unicode=Truecharset="utf8")

    db = MySQLdb.connect (host = "localhost", user = "root", passwd = "", db = "testdb", use_unicode = True, charset = "utf8") – 김경훈 김경훈 2014-03-13 17:04

세부 사항 참조 :

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')데이터베이스에 넣기 전에 실행해야 합니다.


You are trying to store a Unicode codepoint \u201c using an encoding ISO-8859-1 / Latin-1 that can't describe that codepoint. Either you might need to alter the database to use utf-8, and store the string data using an appropriate encoding, or you might want to sanitise your inputs prior to storing the content; i.e. using something like Sam Ruby's excellent i18n guide. That talks about the issues that windows-1252 can cause, and suggests how to process it, plus links to sample code!


SQLAlchemy users can simply specify their field as convert_unicode=True.

Example: sqlalchemy.String(1000, convert_unicode=True)

SQLAlchemy will simply accept unicode objects and return them back, handling the encoding itself.

Docs


Latin-1 (aka ISO 8859-1) is a single octet character encoding scheme, and you can't fit \u201c () into a byte.

Did you mean to use UTF-8 encoding?


Use the below snippet to convert the text from Latin to English

import unicodedata
def strip_accents(text):
    return "".join(char for char in
                   unicodedata.normalize('NFKD', text)
                   if unicodedata.category(char) != 'Mn')

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

output:

'aeinouu'


Python: You will need to add # - * - coding: UTF-8 - * - (remove the spaces around * ) to the first line of the python file. and then add the following to the text to encode: .encode('ascii', 'xmlcharrefreplace'). This will replace all the unicode characters with it's ASCII equivalent.

참고URL : https://stackoverflow.com/questions/3942888/unicodeencodeerror-latin-1-codec-cant-encode-character

반응형