【发布时间】:2017-12-09 05:20:10
【问题描述】:
我有一个如下所示的文本文件:
- l\u00f6yt\u00e4\u00e4
但所有 unicode 字符都需要替换为相应的字符,应该如下所示:
- loytää
问题是我不想自己替换所有 unicode 代码,自动执行此操作的最有效方法是什么? 我的代码现在看起来像这样,但它确实需要改进!(代码在 Python3 中)
import io
input = io.open("input.json", "r", encoding="utf-8")
output = io.open("output.txt", "w", encoding="utf-8")
with input, output:
# Read input file.
file = input.read()
file = file.replace("\\u00e4", "ä")
# I think last line is the same as line below:
# file = file .replace("\\u00e4", u"\u00e4")
file = file.replace("\\u00c4", "Ä")
file = file.replace("\\u00f6", "ö")
file = file.replace("\\u00d6", "Ö")
.
.
.
# I cannot put all codes in unicode here manually!
.
.
.
# writing output file
output.write(file)
【问题讨论】:
-
使用 encoding = "UTF-16" 或 "UTF-16LE",应该可以解决问题。
-
@AndoJurai:不,它确实不能解决问题。数据包含 JSON 转义序列,而不是 UTF-16 数据。
-
好的,谢谢,我学到了一些东西。我只是期望一个众所周知的标准遵守通常的编码规则。有趣的是,它对不寻常的字符有自己的编码。如果输入足够,不能通过“编码”参数进行处理,还是您提出的解决方案是唯一的?
标签: python json python-3.x unicode unicode-string