簡體   English   中英

如何將文本文件中二進制字符串的字符串表示形式轉換回它來自的 utf8 編碼文本?

[英]How to convert the string representation of a binary string froma text file back into the utf8 encoded text it came from?

我有一個俄語詞:“привет”。 它使用'привет'.encode('utf-8')編碼為 utf-8 字節,結果是 python 字節對象表示為:

b'\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82'

現在我將它保存在一個文件中,當我閱讀該文件時,我得到了這個字符串: "b'\\\\xd0\\\\xbf\\\\xd1\\\\x80\\\\xd0\\\\xb8\\\\xd0\\\\xb2\\\\xd0\\\\xb5\\\\xd1\\\\x82'"

如何將此字符串解碼為原始單詞?

它不是我試圖解碼的字節對象,而是一個字符串,所以

"b'\\xd0\\xbf\\xd1\\x80\\xd0\\xb8\\xd0\\xb2\\xd0\\xb5\\xd1\\x82'".decode('utf-8') 

返回AttributeError: 'str' object has no attribute 'decode'

我將它保存到文件的方式只是通過調用logger.info(x.encode('utf-8'))這是

import logging 
logger = logging.getLogger('GENERATOR_DYNAMICS')

我讀取文件的方式是

with open('file.log') as f:
    logs = f.readlines()

你的問題有兩方面:

  • 你得到了字節數組的字符串表示(來自文件,但那是無關緊要的)
  • 您想將字節數組恢復為 utf8 文本

所以解決方案也是兩步:

import ast

# convert string representation back into binary
string_rep = "b'\\xd0\\xbf\\xd1\\x80\\xd0\\xb8\\xd0\\xb2\\xd0\\xb5\\xd1\\x82'"
as_binary = ast.literal_eval(string_rep)

# convert binary to utf8
text = as_binary.decode("utf8")
 

再次獲得'привет'

最后一部分是Python3的副本:解碼 UTF-8 字節轉換為字符串

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM