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

标签 python unicode utf-8 lua torch

我在尝试解码特定的 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 代理项上,理解这意味着我可以针对不同的值过滤/切换它们。在此用例中,这不是什么大问题。

关于python - lua cjson 无法解码特定的 unicode 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39318257/

相关文章:

php - 在 Oracle 和 PHP 中使用 Unicode

java - Spring RestTemplate 字符集 UTF-8 不起作用

python - 如何在 Python 中将方法作为参数传递

用于文件上传和持久连接的python库?

python - 如何在 Windows XP 上使用 pip 安装 selenium 包?

python - Pyspark - 计算 groupby 的实际值和预测值之间的 RMSE - AssertionError : all exprs should be Column

perl - 如何在 Perl 中识别货币符号?

sql - 来自Grails中的unicode的SQL语法错误(度数为\u00B0)

python - 无需解压即可在 python 中读取 *.tar.gz 文件

c++ - 使用 std::locale 格式化法语数字时,UTF-8 数据无效