Python unicode文件写入

标签 python json unicode utf-8

我正在使用 twitter python 库从公共(public)流中获取一些推文。该库以 json 格式获取推文并将其转换为 python 结构。我想做的是直接获取 json 字符串并将其写入文件。在 twitter 库内部,它首先读取网络套接字并将 .decode('utf8') 应用于缓冲区。然后,它将信息包装在 python 结构中并返回它。我可以使用 jsonEncoder 将其编码回 json 字符串并将其保存到文件中。但我猜字符编码有问题。当我尝试打印 json 字符串时,它在控制台中打印得很好。但是当我尝试将其写入文件时,会出现一些字符,例如 \u0627\u0644\u0644\u06be\u064f

我尝试使用不同的编码打开保存的文件,但没有任何变化。它应该采用 utf8 编码,当我尝试显示它时,这些特殊字符应该替换为它们代表的实际字符。我在这里错过了什么吗?我怎样才能实现这个目标?

更多信息:

我使用的是 python 2.7

我像这样打开文件:

json_file = open('test.json', 'w')

我也尝试过这个:

json_file = codecs.open( 'test.json', 'w', 'utf-8' )

一切都没有改变。我盲目地在json字符串上尝试了.encode('utf8').decode('utf8'),结果是一样的。我尝试了不同的文本编辑器来查看书面文本,我使用 cat 命令在控制台中查看文本,并且那些以 \u 开头的字符仍然出现。

更新:

我解决了这个问题。 jsonEncoder 有一个选项 ensure_ascii

If ensure_ascii is True (the default), all non-ASCII characters in the output are escaped with \uXXXX sequences, and the results are str instances consisting of ASCII characters only.

我把它设为False,问题就消失了。

最佳答案

jsonEncoder 有一个选项 Ensure_ascii

If ensure_ascii is True (the default), all non-ASCII characters in the output are escaped with \uXXXX sequences, and the results are str instances consisting of ASCII characters only.

将其设置为False,问题就会消失。

关于Python unicode文件写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20306249/

相关文章:

Python pandas 模仿 excel 数据透视表

python - python中重复gzip文件

python - 如何在 python 中解码 JPG/PNG?

jquery - 通过 ajax 调用 CouchDB 时得到空响应

python - mac 运行 deepfakes - faceswap ' faceswap.py' 出现错误

ruby-on-rails - 如何使用 ActiveRecord json 字段类型

调整div大小的javascript代码

SQL Server,如何将默认排序规则设置为unicode?

iphone - 当 unicode 文本在 iPhone 中的字符串中时字符串的高度

python - 如何将 unicode 原始文字解码为可读字符串?