使用 python 3 读取十六进制字符并将它们转换为 utf-8 [英] Read hex characters and convert them to utf-8 using python 3

查看:42
本文介绍了使用 python 3 读取十六进制字符并将它们转换为 utf-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含此字符串的文件 data.txt:

I have a file data.txt containing this string:

M\xc3\xbchle\x0astra\xc3\x9fe

现在需要读取文件并将十六进制代码解释为 utf-8.

Now the file needs to be read and the hex code interpreted as utf-8.

到目前为止,这是我的尝试:

So far this is my try:

#!/usr/bin/python3

import os
import sys

with open("data.txt") as f:
    for line in f.readlines():
        print( bytes(line, 'utf-8').decode("unicode_escape"))

输出转换换行符 (\x0a),但不适用于多字节 utf-8 字符:

The output converts the newline (\x0a), but does not work with multi-byte utf-8 characters:

Mühle
straÃe

推荐答案

尝试

line = line.decode('unicode_escape').encode('latin-1').decode('utf8')

这篇关于使用 python 3 读取十六进制字符并将它们转换为 utf-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆