大佬教程收集整理的这篇文章主要介绍了从文件中读取 str 包含十六进制字节 str 字符并解码?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个文件 example.log
,其中包含:
<POOR_IN200901UV xmlns="urn:hl7-org:v3"
xmlns:xsi="http://www.w3.org/2001/XMLscheR_500_11845@a-instance" ITsversion="XML_1.0"
xsi:scheR_500_11845@aLOCATIOn="urn:hl7-org:v3
../../scheR_500_11845@as/POOR_IN200901UV20.xsd">\n\t<!-- \xe6\xb6\x88\xe6\x81\xafID -
->\n\t<ID extension="BS002"/>
我想读取文件并将 str 转换为 utf-8
编码格式并写入新文件。目前我的代码如下:
with open("example_decoded.log",'w') as f:
for line in open("example.log",'r',enCoding='utf-8'):
m = re.search("<POOR_IN200901UV",linE)
if m:
line = line[m.start():-2]
line_bytes = bytes(line,enCoding='raw_unicode_escape')
line_decoded = line_bytes.decode('utf-8')
print(line_decoded)
f.write(line_decoded)
else:
pass
但是 example_decoded.log
的内容:
<POOR_IN200901UV xmlns="urn:hl7-org:v3"
xmlns:xsi="http://www.w3.org/2001/XMLscheR_500_11845@a-instance" ITsversion="XML_1.0"
xsi:scheR_500_11845@aLOCATIOn="urn:hl7-org:v3
../../scheR_500_11845@as/POOR_IN200901UV20.xsd">\n\t<!-- \xe6\xb6\x88\xe6\x81\xafID -
->\n\t<ID extension="BS002"
\xe6\xb6\x88\xe6\x81\xaf
部分没有被解码,所以我想知道如何处理这个混合类型的 str 解码问题?
decodedVal = struct.unpack(">f",bytes.fromhex(encdoded_val))[0]
请参阅以下链接以添加您的字节序并键入而不是 ">f"
https://docs.python.org/3/library/struct.html
,import codecs
decode_hex = codecs.getdecoder("hex_codec")
String = decode_hex(String)[0]
https://docs.python.org/3/library/codecs.html
,参考:Read hex characters and convert them to utf-8 using python 3
with open("example_decoded.log",'w') as f:
for line in open("example.log",'r',encoding='utf-8'):
m = re.search("<POOR_IN200901UV",linE)
if m:
line = line[m.start():-2]
line_decoded = bytes(line,'utf-8').decode('unicode_escape').encode('laTin-1').decode('utf8')
print(line_decoded)
f.write(line_decoded)
else:
pass
以上是大佬教程为你收集整理的从文件中读取 str 包含十六进制字节 str 字符并解码?全部内容,希望文章能够帮你解决从文件中读取 str 包含十六进制字节 str 字符并解码?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。