【问题标题】:Replace all unicode codes with characters in python用python中的字符替换所有unicode代码
【发布时间】: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


【解决方案1】:

只需将 JSON解码为 JSON,然后在不确保数据是 ASCII 安全的情况下写出新的 JSON 文档:

import json

with open("input.json", "r", encoding="utf-8") as input:
    with open("output.txt", "w", encoding="utf-8") as output:
        document = json.load(input)
        json.dump(document, output, ensure_ascii=False)

来自json.dump() documentation

如果 ensure_ascii 为真(默认值),则保证输出所有传入的非 ASCII 字符都已转义。如果 ensure_ascii 为 false,这些字符将按原样输出。

演示:

>>> import json
>>> print(json.loads(r'"l\u00f6yt\u00e4\u00e4"'))
löytää
>>> print(json.dumps(json.loads(r'"l\u00f6yt\u00e4\u00e4"')))
"l\u00f6yt\u00e4\u00e4"
>>> print(json.dumps(json.loads(r'"l\u00f6yt\u00e4\u00e4"'), ensure_ascii=False))
"löytää"

如果您有非常大的文档,您仍可以逐行逐行处理它们,但使用正则表达式进行替换:

import re

unicode_escape = re.compile(
    r'(?<!\\)'
    r'(?:\\u([dD][89abAB][a-fA-F0-9]{2})\\u([dD][c-fC-F][a-fA-F0-9]{2})'
    r'|\\u([a-fA-F0-9]{4}))')
def replace(m):
    return bytes.fromhex(''.join(m.groups(''))).decode('utf-16-be')

with open("input.json", "r", encoding="utf-8") as input:
    with open("output.txt", "w", encoding="utf-8") as output:
        for line in input:
            output.write(unicode_escape.sub(replace, line))

但是,如果您的 JSON 在字符串中嵌入了 JSON 文档,或者转义序列前面有一个 转义 反斜杠,则此操作会失败。

【讨论】:

  • 太棒了,谢谢你的好解决方案 ;-) 但是你能想到其他不需要处理文本文件的方法吗?或者也许更快地处理它们?我按照你说的做了,因为我是在非常大的 json 文件上做这个,它太慢了。
  • @Pedram:我添加了逐行替换选项。它会在一定程度上起作用
  • 您确定逐行解决方案适用于需要代理点的字符吗?例如。 “?”,在 JSON 中表示为 "\\ud83e\\udd5d"。 (或者这就是你所说的“达到一定程度”的意思?)
  • @lenz:是的,就是其中之一。您必须添加一个单独的正则表达式,首先应用它来查找代理对并将其解码为一系列 UTF-16 字节。
猜你喜欢
  • 2011-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-31
  • 1970-01-01
  • 1970-01-01
  • 2018-05-14
  • 1970-01-01
相关资源
最近更新 更多