gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:03:32 25 4
gpt4 key购买 nike

将属性转换为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com