在不引入大量/看似错误的反斜杠+未转换的unicode字符的情况下,我在将压缩的十六进制编码字符串转换回其原始格式时遇到了麻烦。
我用来做这个过程的代码是:import gzip
from io import StringIO, BytesIO
def string_to_bytes(input_str: str) -> bytes:
"""
Read the given string, encode it in utf-8, gzip compress
the data and return it as a byte array.
"""
bio = BytesIO()
bio.write(input_str.encode("utf-8"))
bio.seek(0)
stream = BytesIO()
compressor = gzip.GzipFile(fileobj=stream, mode='w')
while True: # until EOF
chunk = bio.read(8192)
if not chunk: # EOF?
compressor.close()
return stream.getvalue()
compressor.write(chunk)
def bytes_to_string(input_bytes: bytes) -> str:
"""
Decompress the given byte array (which must be valid
compressed gzip data) and return the decoded text (utf-8).
"""
bio = BytesIO()
stream = BytesIO(input_bytes)
decompressor = gzip.GzipFile(fileobj=stream, mode='r')
while True: # until EOF
chunk = decompressor.read(8192)
if not chunk:
decompressor.close()
bio.seek(0)
return bio.read().decode("utf-8")
bio.write(chunk)
return None
在脚本中,我正在运行的input_string
被压缩+保存为十六进制:
saved_hex = string_to_bytes(input_string).hex()
这将作为BINARY数据类型存储在Snowflake数据库中(使用HEX二进制格式)。
从那里加载出来,像这样:
hex_bytes = bytes.fromhex(hex_html)
html_string = bytes_to_string(hex_bytes)
结果如下:
href\\\\u003d\\\\\\x22https://www.google.com/advanced_search\\\\\\x22 target\\\\u003d\\\\\\x22_blank\\\\\\x22\\\\u003eadvanced search\\\\u003c/a\\\\u003e to find results...
如果有多个反斜杠,我无法将其转换回单个反斜杠(在unicode字符的情况下)或完全删除。
有没有办法更有效地:
- Gzip压缩字符串
- 转换为十六进制
- 解码十六进制+解压-不添加任何这些奇怪的未转换unicode字符?
感谢大家的回答-我愚蠢地意识到:
- 我正在向输入字符串添加额外的
json.dumps()
(进一步将其编码为字符串并添加所有额外的反斜杠)。 - Snowflake将数据保存为字节,必须先使用
TO_VARCHAR(saved_hex_data)
将其转换为二进制,然后才能调用bytes_to_string(bytes.fromhex(output_string))
。
此时一切保持原样,再次感谢。