gpt4 book ai didi

python - Python 2.7在python中同时解码UTF-8和unicode-escape会导致UnicodeEncodeError

转载 作者:行者123 更新时间:2023-12-02 10:51:13 26 4
gpt4 key购买 nike

我有一个tsv文件,在某些行中的特定列包含混合格式,例如:Hapoel_Be\u0027er_Sheva_A\u002eF\u002eC\u002e应该是Hapoel_Be'er_Sheva_A.F.C.

这是我用来读取文件并拆分列的代码:

with open(path, 'rb') as f:
for line in f:
cols = line.decode('utf-8').split('\t')
text = cols[3].decode('unicode-escape') #Here is the column that has the above mentioned mixed format

错误信息:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0160' in position 6: ordinal not in range(128)

我想知道在读取文件时如何从第一种混合格式转换为另一种格式吗?我正在使用python 2.7。

非常感谢,

最佳答案

您可以使用ast.literal_eval将原始字节转换为unicode

import ast

raw_bytes = br'Hapoel_Be\u0027er_Sheva_A\u002eF\u002eC\u002e'
print(raw_bytes) # b'Hapoel_Be\u0027er_Sheva_A\u002eF\u002eC\u002e'

unicode_string = ast.literal_eval('"{}"'.format(raw_bytes.decode('utf8')))
unicode_string的输出:
Hapoel_Be'er_Sheva_A.F.C.

更新-在python 2.7中进行了测试并具有魅力

关于python - Python 2.7在python中同时解码UTF-8和unicode-escape会导致UnicodeEncodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52207648/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com