Skip to main content
 首页 » 编程设计

python之ast.literal_eval 以某种方式抛出 UnicodeDecodeError

2025年05月04日7zengkefu

好吧...

  • Unicode 字符串被编码为 Python 2.x 字符串(实际上是字节序列)
  • Python 2.x 字符串被解码为 Unicode 字符串

Python UnicodeDecodeError - Am I misunderstanding encode?

我有这个 python 2.7 代码

try: 
    print '***' 
    print type(relationsline) 
    relationsline = relationsline.decode("ascii", "ignore") 
    print type(relationsline) 
    relationsline = relationsline.encode("ascii", "ignore") 
    print type(relationsline) 
    relations = ast.literal_eval(relationsline) 
except ValueError: 
    return 
except UnicodeDecodeError: 
    return 

上面代码的最后一行有时会抛出

UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 341: ordinal not in range(128)

我认为这将 (1) 以具有某种(未知)编码的字符串开头 (2) 将其解码为 un​​icode 类型,代表一串字符 unicode 字符集采用 ascii 编码,同时忽略所有可能的字符't be encoded with ascii (3) 将unicode类型编码为ascii编码的字符串,忽略所有不能用ascii表示的字符。

这是完整的堆栈跟踪:

Traceback (most recent call last): 
  File "outputprocessor.py", line 69, in <module> 
    getPersonRelations(lines, fname) 
  File "outputprocessor.py", line 41, in getPersonRelations 
    relations = ast.literal_eval(relationsline) 
  File "/usr/lib/python2.7/ast.py", line 49, in literal_eval 
    node_or_string = parse(node_or_string, mode='eval') 
  File "/usr/lib/python2.7/ast.py", line 37, in parse 
    return compile(source, filename, mode, PyCF_ONLY_AST) 
  File "<unknown>", line 1 
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 341: ordinal not in range(128) 
                      ^ 
SyntaxError: invalid syntax 

但这在某处显然是错误的。更令人困惑的是 UnicodeDecodeError 没有捕获 UnicodeDecodeError。我错过了什么?也许这是问题所在? http://bugs.python.org/issue22221

请您参考如下方法:

仔细查看堆栈跟踪。它抛出一个 SyntaxError。

您正在尝试literal_eval 字符串“UnicodeDecodeError:‘ascii’编解码器无法解码位置 341 中的字节 0xfc:序号不在范围 (128) 内”。您可以根据需要对该字符串进行编码/解码,但 ast 不知道如何处理它 - 这显然不是有效的 python 文字。

参见:

>>> import ast 
>>> ast.literal_eval('''UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 341: ordinal not in range(128)''') 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  File "/usr/lib/python2.7/ast.py", line 49, in literal_eval 
    node_or_string = parse(node_or_string, mode='eval') 
  File "/usr/lib/python2.7/ast.py", line 37, in parse 
    return compile(source, filename, mode, PyCF_ONLY_AST) 
  File "<unknown>", line 1 
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 341: ordinal not in range(128) 
                      ^ 
SyntaxError: invalid syntax 

我会查看将这些字符串传递给您的函数的任何来源,它正在生成一些虚假输入。