Skip to main content
 首页 » 编程设计

python之lua cjson 无法解码特定的 unicode 字符

2025年04月02日8qq78292959

我在尝试解码特定的 unicode 字符时从 lua cjson 收到以下错误,

root@9dc8433e6d83:~/torch-rnn# th train.lua -input_h5 data/aud.h5 -input_json data/aud.json -batch_size 50 -seq_length 100 -rnn_size 256 -max_epochs 50 
Running with CUDA on GPU 0   
/root/torch/install/bin/luajit: train.lua:77: Expected value but found invalid unicode escape code at character 350873 
stack traceback: 
    [C]: in function 'read_json' 
    train.lua:77: in main chunk 
    [C]: in function 'dofile' 
    /root/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:145: in main chunk 
    [C]: at 0x00406670 

通过跟踪源代码,我可以看到 train.lua read_json 正在使用 cjson。

有问题的 unicode 转义码是\uda85

如果我去https://www.branah.com/unicode-converter它告诉我转义应该解码到的字符。

unicode 转义是使用 python unichr(55941) 生成的,并通过 python 脚本输出的重定向写入 PYTHONIOENCODING=UTF-8 的文件。

下面演示字符是如何生成的;

echo "print unichr(55941)" > test.py 
python test.py 
Traceback (most recent call last): 
  File "test.py", line 1, in <module> 
    print unichr(55941) 
UnicodeEncodeError: 'ascii' codec can't encode character u'\uda85' in position 0: ordinal not in range(128) 
 
# export PYTHONIOENCODING=UTF-8 
# python test.py 
��� 
# python test.py > tfile 
# cat tfile 
��� 
# python 
Python 2.7.6 (default, Jun 22 2015, 17:58:13)  
[GCC 4.8.2] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> f=open("tfile",'r') 
>>> s=f.readline() 
>>> s 
'\xed\xaa\x85\n' 
>>> print s 
��� 
 
>>> s.decode('utf-8') 
u'\uda85\n' 

我总体上想做的是取一组 0-65535 范围内的整数,并使用 python 将它们映射到 UTF-8 字符并将它们写到一个文件中。然后我想使用使用 LUA 的 torch-rnn 在字符序列上训练 RNN。尝试在 torch-rnn python 脚本/preprocess.py 生成的文件上运行 train.lua 时出现错误

请您参考如下方法:

问题似乎出在 unicode 代理项上,理解这意味着我可以针对不同的值过滤/切换它们。在此用例中,这不是什么大问题。