gpt4 book ai didi

Python - Unicode 解码/编码

转载 作者:太空宇宙 更新时间:2023-11-03 15:32:03 24 4
gpt4 key购买 nike

我如何传递所有来自创建数据库输入 (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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com