Python - Unicode 解码/编码

标签 python encoding character-encoding python-unicode

我如何传递所有来自创建数据库输入 (s1) 的内容,从那里加载它 (s2) 并将其正确地返回格式传递给文件?

import time,os,sys,base64
s = "Hello World!\r\nHeyho"
#with s1 i make an input to the database; with s2 I select it -> works most time
s1 = base64.b64encode(s.encode("UTF-8")).decode("UTF-8") #print("Base64 Encoded:", s1)
s2 = base64.b64decode(s1.encode("UTF-8")).decode("UTF-8") #print(s2)

#example that I try to save it in a file:
s3 = "PGhlYWQ+CiAgICA8dGl0bGU+4pa3IEltbW9iaWxpZW4gLSBIw6R1c2VyIC0gV29obnVuZ2VuIC0gZmluZGVuIGJlaSBpbW1vd2VsdC5kZTwvdGl0bGU+"
with open("C:\\Users\\001\\Downloads\\Output.txt", "w") as text_file:
    text_file.write("Ausgabe: %s" % base64.b64decode(s3.encode("UTF-8")).decode("UTF-8")) #with .encode('ascii', 'ignore') i whould delete the signs

日志:

C:\Users\001\Downloads>python trythis.py
Traceback (most recent call last):
  File "trythis.py", line 11, in <module>
    text_file.write("Ausgabe: %s" % base64.b64decode(s3.encode("UTF-8")).decode("UTF-8")) #with .encode('ascii', 'ignore') i whould delelte signs
  File "C:\Users\001\AppData\Local\Programs\Python\Python35\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u25b7' in position 28: character maps to <undefined>

编辑:我在 Windows 上工作。

C:\Users\001\Downloads>python -V
Python 3.5.2

最佳答案

问题是您以文本模式打开文件,但没有指定编码。在这种情况下,将使用系统默认编码,这在任何系统上都可能不同。

解决方案:将编码参数指定给open() .

作为旁注:你为什么要.decode('UTF-8')?它确实有效,但由于数据是 Base64 编码的,我认为 ASCII 解码更有意义。此外,您应该只在 I/O 边界进行编码/解码(因此在这种情况下写入文件时),尽管在这种情况下您可能只是出于测试/演示目的而这样做。

更新:

显然,您的 Base64 编码数据也是 UTF-8 编码的(首先是 UTF-8,然后是 Base64),因此您需要先对其进行 Base64 解码,然后再进行 UTF-8 解码。

以下是一个可移植的工作示例:

import base64

b64_encoded_text = 'PGhlYWQ+CiAgICA8dGl0bGU+4pa3IEltbW9iaWxpZW4gLSBIw6R1c2VyIC0gV29obnVuZ2VuIC0gZmluZGVuIGJlaSBpbW1vd2VsdC5kZTwvdGl0bGU+'
decoded_text = base64.b64decode(b64_encoded_text).decode('utf-8')

with open('Output.txt', 'wt', encoding='utf-8') as text_file:
    text_file.write('Ausgabe: %s' % decoded_text)

尽管将原始二进制(UTF-8 编码)数据写入文件更容易:

import base64

b64_encoded_text = 'PGhlYWQ+CiAgICA8dGl0bGU+4pa3IEltbW9iaWxpZW4gLSBIw6R1c2VyIC0gV29obnVuZ2VuIC0gZmluZGVuIGJlaSBpbW1vd2VsdC5kZTwvdGl0bGU+'

with open('Output.txt', 'wb') as file:
    # file.write(b'Ausgabe: ')  # uncomment if really needed
    file.write(base64.b64decode(b64_encoded_text))

关于Python - Unicode 解码/编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57477217/

相关文章:

python - 使用 PuLP 的 3D 装箱

python - 如何捕捉一组最长的序列

java - JNA:仅更改一个外部 native 库的字符串编码

php - UTF8 中的特殊字符 mailto : subject= link and Outlook

php - 如何用 PHP 中的特殊字符替换特殊字符?

windows - 如何将 encodingName 转换为 codePage 标识符?

ruby - URI.unescape 在尝试将 "%C3%9Fą"转换为 "ßą"时崩溃

python - 如何在 Azure Devops 上的 ubuntu 镜像中为 matplotlib 使用 TkAgg 后端?

python - markdown2 模块 - 如何从 Python 脚本中转换 markdown 文件?

mysql - 使用 Mysql 和 Hibernate 时表情符号的字符集编码问题