python - 使用正则表达式将转义的双引号替换为 Python 中的单引号
问题描述
我正在尝试将键值对中的转义双引号替换为单引号
import re
import json
js = r'{"result":"{\"key\":\"How are you? \"Great!\" he said. \"Coffee ?\"\"},{\"key\":\" 2. \"Why not sure\". They walked away\"}"}'
#print(js)
data1 = json.loads(js)
s = data1['result']
#print(s)
# {"key":"How are you? "Great!" he said. "Coffee ?""},{"key":" 2. "Why not, sure.". They walked away"}
p = re.compile(r"\"key\":\"(.*\"(.*)\".*)\"")
print(p.sub(r'\'\2\'',s))
# {\'Why not, sure.\'}
json_string = "[{0}]".format(p.sub(r'\'\1\'',s))
data_list = json.loads(json_string)
使用上面的代码,我得到了一个输出 \'Coffee ?\' 而不是整个字符串。我想只在值部分替换双引号。
String : "key":"你好吗?"太好了!"他说。"咖啡?"",
预期字符串: “key”:“你好吗?'太好了!' 他说。'咖啡?'",
解决方案
这个答案只是在我们交换的评论之后:
import json
js = r'{"result":"{\"key\":\"How are you? \"Great!\" he said. \"Coffee ?\"\"},{\"key\":\" 2. \"Why not sure\". They walked away\"}"}'
data1 = json.loads(js)
s = data1['result']
good_characters = [":","{","}", ","]
result = ""
for key, value in enumerate(s):
if (value == "\"" and s[key-1] not in good_characters) and (value == "\"" and s[key+1] not in good_characters):
result += '\''
else:
result += value
print (result)
输出
{"key":"How are you? 'Great!' he said. 'Coffee ?'"},{"key":" 2. 'Why not sure'. They walked away"}
推荐阅读
- python - 为每个图像找到两个最近的
- javascript - 列出页面的 javascript url
- c# - 如何从抽象基类多重继承?
- vue.js - 使用 vue 自定义元素
- dafny - 在 dafny 中修改返回变量
- git - 使用 pre-commit.com,如何修复 go vet 错误“没有 Go 文件”
- vba - Outlook VBA 获取日期范围内的所有 AppointmentItems 并将它们作为集合返回
- oracle - 在 NULL 1 上更改默认值时缺少表达式
- python - 如何在制作直方图时在 matpotlib 中定义变量
- amazon-iam - AWS IAM 和 CLI - 如何解决传递角色错误?