python - 如何在Python中用ASCII字符(\u9078)分割行

标签 python python-3.x

将属性转换为 JSON 时,会在 ASCII 字符中添加额外的反斜杠,如何避免这种情况,请参阅下面的代码

输入文件(sample.properties)

property.key.CHOOSE=\u9078\u629e

代码

import json
def convertPropertiesToJson(fileName, outputFileName, sep='=', comment_char='#'):
    props = {}
    with open(fileName, "r") as f:
        for line in f:
            l = line.strip()
            if l and not l.startswith(comment_char):
                innerProps = {}
                keyValueList = l.split(sep)
                key = keyValueList[0].strip()
                keyList = key.split('.')
                value = sep.join(keyValueList[1:]).strip()
                if keyList[1] not in props:
                    props[keyList[1]] = {}
                innerProps[keyList[2]] = value
                props[keyList[1]].update(innerProps)
    with open(outputFileName, 'w') as outfile:
        json.dump(props, outfile)

convertPropertiesToJson("sample.properties", "sample.json")

输出:(sample.json)

{"key": {"CHOOSE": "\\u9078\\u629e"}}

预期结果:

{"key": {"CHOOSE": "\u9078\u629e"}}

最佳答案

问题是输入按原样读取,而 \u 被逐字复制为两个字符。最简单的修复可能是这样的:

with open(fileName, "r", encoding='unicode-escape') as f:

这将解码转义的 unicode 字符。

关于python - 如何在Python中用ASCII字符(\u9078)分割行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49313692/

相关文章:

python - 按 Pandas 中的列子值排序

python - 使用 Sphinx 格式化多行文档字符串

python - 使用返回 HTTP 400 的 Firestore REST API 创建新的集合和文档

python - 如何使用我在 python 中创建的简单模块?

python - 如何使用 Pandas 获取列中特定值的计数

python - 如何将 Python dict 序列化为 JSON

python - numpy.ndarray 枚举适当的维度子集?

python - 如何获取 pathlib.Path 对象的绝对路径?

python - 将值移出对象

python - 从 python 帮助中提取示例到 ipython session 中