在Python3.9中使用正则表达式在已知分隔符之间提取文本(以“johab”编码)

2024-10-02 18:24:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在已知分隔符之间提取提取文本(以“johab”编码编码)[见下文]。理想情况下,我希望将所有提取的文本转储到一个文本文件中

Here is a screenshot of my hex editor in Johab clearly displaying the Hangeul characters properly 文本始终以“\v”(十六进制:5C 76)开头,以新行“\n”(十六进制:5C 6E)或“\e”结尾

我以前也用过同样的代码片段来提取一组字节之间的文本,它工作起来没有问题。。。这一次我得到一个错误,当我解码的文字使用约翰。。。我知道它是在约翰福音中编码的,所以我不明白为什么会发生这种情况。当然,我可以通过尝试和传球来忽略错误,但似乎它无法解码一切。 UnicodeDecodeError:“johab”编解码器无法解码位置1:非法多字节序列中的字节0x97

import re

with open(path_to_file,'rb') as data: #open file filename in read mode
    buffer = data.read()#read content

text = re.findall(b'\\x5C\\x76(.*)\\x5C', buffer, re.MULTILINE)
print ("DECODING...")

for i in range(len(text)):
  #try:
    text[i] = text[i].decode('johab')
  #except:
  #  pass

print("DECODING COMPLETE.\nEXPORTING TO LOGS...")
print (text)
with open(output_path, 'w', encoding='johab') as f:
    for item in text:
        f.write("%s\n" % item)

print("EXPORTING COMPLETE.")

Tags: pathtextin文本re编码read字节