使用正则表达式在Python中将转义的双引号替换为单引号 [英] Replace escaped double quotes to single quotes in Python using regex

查看:1039
本文介绍了使用正则表达式在Python中将转义的双引号替换为单引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将键值对中的转义双引号替换为单引号

I am trying to replace escaped double quotes to single quotes in a key value pair

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?\',而不是整个字符串.我只想在值部分内替换双引号.

With the above code, I got an output \'Coffee ?\' instead of the entire string. I would like to replace the double quote only within the value part.

字符串:键":你好吗?"太好了!他说."咖啡吗?,"

String : "key":"How are you? "Great!" he said. "Coffee ?"",

期望的字符串:键":你好吗?他说:咖啡吗?",

Expected String : "key":"How are you? 'Great!' he said. 'Coffee ?'",

推荐答案

此答案仅在我们交换的评论之后:

This answer is just following the comments we've exchanged:

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中将转义的双引号替换为单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆