4 回答

TA貢獻1824條經驗 獲得超6個贊
您可以使用re.findall獲取所有匹配值對,然后將該列表轉換為dict:
import re
s = 'a:b# c:d# e:f#'
d = dict(re.findall(r'(\w+):(\w+)#', s))
print(d)
輸出:
{'a': 'b', 'c': 'd', 'e': 'f'}
要將其轉換為 JSON 字符串,請使用json.dumps:
import json
print(json.dumps(d))
輸出:
{"a": "b", "c": "d", "e": "f"}

TA貢獻1780條經驗 獲得超4個贊
刪除#,然后在空間上拆分以獲得零件,然后拆分:以配對映射
s = 'a:b# c:d# e:f#'
res = dict(v.split(':') for v in s.replace("#", "").split())
print(res) # {'a': 'b', 'c': 'd', 'e': 'f'}

TA貢獻1847條經驗 獲得超11個贊
這不是最快/最短的解決方案。但是我認為它可能是最容易被初學者理解的。
然后,您可以根據需要縮短/優化代碼。
你的問題由兩部分組成。
1.) 如何將特定格式的字符串轉換為 python 數據結構
2.) 如何將 python 數據結構轉換為 json
import json
def my_parse(data_str):
result = {}
entries = data_str.split('#') # split input by '#'
for entry in entries:
entry = entry.strip() # remove leading and trailing white space
if entry: #
key, val = entry.split(":")
# cleanup key and val. (strip off spaces) perhaps you don't need this
key = key.strip()
val = val.strip()
result[key] = val # add to our dict
return result
example_data = 'a:b# c:d# e:f#'
rslt_dict = my_parse(example_data)
print("result dict is", rslt_dict)
# convert to json string.
json_str = json.dumps(rslt_dict)
# or directly write json to file
with(open("myjsonfile.json", "w")) as fout:
json.dump(rslt_dict, fout)

TA貢獻1826條經驗 獲得超6個贊
import re
import json
str = 'a:b# c:d# e:f#' # input string
kv = re.compile("(\w):(\w)") # prepare regular expression
l = kv.findall(str) # find all <key>:<value> pairs
d = dict(l) # convert list to dict
j = json.dumps(d) # generate JSON
print( d )
印刷
{'a': 'b', 'c': 'd', 'e': 'f'}
添加回答
舉報