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

标签 python text unicode encoding compiler-errors

我有一个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/

相关文章:

python - LSTM 预测一条直线

python - 将文本文件转换为列表并使用索引 : 获取它

c# - .NET Framework中是否有ReadWord()方法?

android - Unicode 和安卓 NDK

python - IBAN 掩码的正则表达式

python - 配置 python 脚本知道它的文件名

python - "dot.exe"在路径中找不到。 Python 上的 Pydot (Windows 7)

jquery - 如何从一组 HTML 片段文件中读取数据?

使用 Unicode 的 JQuery AJAX 调用。 POST Unicode 数据的正确方法?

python - 如果 python unicode 对象被错误解码怎么办