IT

인코딩 / 디코딩의 차이점은 무엇입니까?

lottoking 2020. 5. 24. 11:47
반응형

인코딩 / 디코딩의 차이점은 무엇입니까?


str / unicode 디코딩과 인코딩의 차이점을 이해하지 못했습니다.

나는 str().decode()당신이 알고있는 바이트 문자열이있을 때 특정 문자 인코딩을 가지고 있고, 인코딩 이름이 유니 코드 문자열을 반환한다는 것을 알고 있습니다.

unicode().encode()주어진 인코딩 이름에 따라 유니 코드 문자를 바이트 문자열로 변환 한다는 것을 알고 있습니다.

그러나 나는 무엇 str().encode()이고 무엇인지 이해하지 못합니다 unicode().decode(). 누구나 위에서 설명하고 잘못한 내용을 설명하고 수정할 수 있습니까?

편집하다:

여러 답변 .encode이 문자열에서 수행하는 작업 에 대한 정보를 제공 하지만 아무도 .decode유니 코드의 기능 을 아는 사람 없습니다 .


decode유니 코드 문자열 방법에는 실제로 응용 프로그램이 전혀 없습니다 (어떤 이유로 유니 코드 문자열에 텍스트가 아닌 데이터가없는 경우는 제외하십시오-아래 참조). 그것은 역사적 이유로 주로 거기에 있다고 생각합니다. 파이썬 3에서는 완전히 사라졌습니다.

unicode().decode()기본 (ascii) 코덱 사용하여 암시 적 인코딩수행합니다 s. 다음과 같이 확인하십시오.

>>> s = u'ö'
>>> s.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)

>>> s.encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)

오류 메시지는 정확히 동일합니다.

들어 str().encode()는 주변의 다른 방법 - 그것은 암시 적 시도 디코딩s기본 인코딩을 :

>>> s = 'ö'
>>> s.decode('utf-8')
u'\xf6'
>>> s.encode()
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)

이렇게 사용하면 str().encode()불필요합니다.

그러나 유용한 후자의 방법의 또 다른 응용이 있습니다. 문자 세트와 관련이없는 인코딩 이 있으므로 8 비트 문자열에 의미있는 방식으로 적용 할 수 있습니다.

>>> s.encode('zip')
'x\x9c;\xbc\r\x00\x02>\x01z'

그러나 두 응용 프로그램 모두에 대한 "인코딩"의 모호한 사용법은 어색합니다. 또, 별도의과 bytestring파이썬 3의 유형이 더 이상 문제가되지 않습니다.


유니 코드 문자열을 바이트 문자열로 나타내는 것을 인코딩이라고 합니다. 사용하십시오 u'...'.encode(encoding).

예:

    >>> u'æøå'.encode ( 'utf8')
    '\ xc3 \ x83 \ xc2 \ xa6 \ xc3 \ x83 \ xc2 \ xb8 \ xc3 \ x83 \ xc2 \ xa5'
    >>> u'æøå'.encode ( 'latin1')
    '\ xc3 \ xa6 \ xc3 \ xb8 \ xc3 \ xa5'
    >>> u'æøå'.encode ( 'ascii')
    UnicodeEncodeError : 'ascii'코덱은 위치 0-5의 문자를 인코딩 할 수 없습니다 : 
    서 수가 범위를 벗어남 (128)

일반적으로 유니 코드 문자열을 IO에 사용해야 할 때마다 (예 : 네트워크를 통해 전송하거나 디스크 파일에 저장).

바이트 문자열을 유니 코드 문자열로 변환하는 것을 디코딩이라고 합니다. 사용 unicode('...', encoding)또는 '...'. 디코딩 (인코딩).

예:

   >>> u'æøå '
   u '\ xc3 \ xa6 \ xc3 \ xb8 \ xc3 \ xa5'# 인터프리터는 유니 코드 객체를 다음과 같이 인쇄합니다.
   >>> 유니 코드 ( '\ xc3 \ xa6 \ xc3 \ xb8 \ xc3 \ xa5', 'latin1')
   u '\ xc3 \ xa6 \ xc3 \ xb8 \ xc3 \ xa5'
   >>> '\ xc3 \ xa6 \ xc3 \ xb8 \ xc3 \ xa5'.decode ('latin1 ')
   u '\ xc3 \ xa6 \ xc3 \ xb8 \ xc3 \ xa5'

일반적으로 네트워크 또는 디스크 파일에서 문자열 데이터를 수신 할 때마다 바이트 문자열을 디코딩합니다.

I believe there are some changes in unicode handling in python 3, so the above is probably not correct for python 3.

Some good links:


anUnicode.encode('encoding') results in a string object and can be called on a unicode object

aString.decode('encoding') results in an unicode object and can be called on a string, encoded in given encoding.


Some more explanations:

You can create some unicode object, which doesn't have any encoding set. The way it is stored by Python in memory is none of your concern. You can search it, split it and call any string manipulating function you like.

But there comes a time, when you'd like to print your unicode object to console or into some text file. So you have to encode it (for example - in UTF-8), you call encode('utf-8') and you get a string with '\u<someNumber>' inside, which is perfectly printable.

Then, again - you'd like to do the opposite - read string encoded in UTF-8 and treat it as an Unicode, so the \u360 would be one character, not 5. Then you decode a string (with selected encoding) and get brand new object of the unicode type.

Just as a side note - you can select some pervert encoding, like 'zip', 'base64', 'rot' and some of them will convert from string to string, but I believe the most common case is one that involves UTF-8/UTF-16 and string.


mybytestring.encode(somecodec) is meaningful for these values of somecodec:

  • base64
  • bz2
  • zlib
  • hex
  • quopri
  • rot13
  • string_escape
  • uu

I am not sure what decoding an already decoded unicode text is good for. Trying that with any encoding seems to always try to encode with the system's default encoding first.


There are a few encodings that can be used to de-/encode from str to str or from unicode to unicode. For example base64, hex or even rot13. They are listed in the codecs module.

Edit:

The decode message on a unicode string can undo the corresponding encode operation:

In [1]: u'0a'.decode('hex')
Out[1]: '\n'

The returned type is str instead of unicode which is unfortunate in my opinion. But when you are not doing a proper en-/decode between str and unicode this looks like a mess anyway.


The simple answer is that they are the exact opposite of each other.

the computer uses the very basic unit of byte to store and process information, it is meaningless for human eyes.

for example,'\xe4\xb8\xad\xe6\x96\x87' is the representation of two Chinese characters, but the computer only knows (meaning print or store) it is Chinese Characters when they are given a dictionary to look for that Chinese word, in this case, it is "utf-8" dictionary, and it would fail to correctly show the intended Chinese word if you look into a different or wrong dictionary(using a different decoding method).

In the above case, the process for a computer to look for Chinese word is decoding().

And the process of computer writing the Chinese into computer memory is encode ().

so the encode information is the raw bytes, and the decoded information is the raw bytes and the name of the dictionary to reference (but not the dictionary itself).

참고URL : https://stackoverflow.com/questions/447107/what-is-the-difference-between-encode-decode

반응형