用ASCII转换十六进制表示法

2024-05-29 10:00:26 发布

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

我试图用pdf文件中的ASCII表示替换十六进制表示(#…)

import re
with open("C:\\Users\\Suleiman JK\\Desktop\\test\\hello-world-malformed.pdf","rb") as file1:
    stuff = file1.read()
stuff = re.sub("#([0-9A-Fa-f]{2})",lambda m:unichr(int(m.groups()[0],16)),stuff)
with open("C:\\Users\\Suleiman JK\\Desktop\\test\\hello-world-malformed.pdf","wb") as file1:
    file1.write(stuff)
file1 = open("C:\\Users\\Suleiman JK\\Desktop\\test\\hello-world-malformed.pdf")
print file1.read()

当我使用“Geany”运行它时,会出现以下错误:

^{pr2}$

Tags: testrehelloworldpdfaswithopen
1条回答
网友
1楼 · 发布于 2024-05-29 10:00:26

不要使用unichr();它生成一个包含一个字符的unicode字符串。不要混合使用Unicode字符串和字节字符串(二进制数据),因为这会触发隐式编码或解码。这里触发隐式解码并失败。在

代码点的值限制为0-255,因此简单的chr()就可以:

stuff = re.sub("#([0-9A-Fa-f]{2})", lambda m: chr(int(m.group(0), 16)), stuff)

相关问题 更多 >

    热门问题