簡體   English   中英

使用正則表達式將 Python 中的轉義雙引號替換為單引號

[英]Replace escaped double quotes to single quotes in Python using regex

我正在嘗試將鍵值對中的轉義雙引號替換為單引號

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)

使用上面的代碼,我得到了 output \'Coffee?\' 而不是整個字符串。 我想只在值部分替換雙引號。

字符串: “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)

Output

{"key":"How are you? 'Great!' he said. 'Coffee ?'"},{"key":" 2. 'Why not sure'. They walked away"}

如果密鑰在字符串中是一致的,那么這將起作用

s = data1['result']
','.join([d[:8] + d[8:-2].replace('"',"'") + d[-2:] for d in s.split(',')])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM