-
慕妹3242003
您可以使用re.findall获取所有匹配值对,然后将该列表转换为dict:import res = '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 jsonprint(json.dumps(d))输出:{"a": "b", "c": "d", "e": "f"}
-
Helenr
删除#,然后在空间上拆分以获得零件,然后拆分:以配对映射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'}
-
回首忆惘然
这不是最快/最短的解决方案。但是我认为它可能是最容易被初学者理解的。然后,您可以根据需要缩短/优化代码。你的问题由两部分组成。1.) 如何将特定格式的字符串转换为 python 数据结构2.) 如何将 python 数据结构转换为 jsonimport jsondef 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 resultexample_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 filewith(open("myjsonfile.json", "w")) as fout: json.dump(rslt_dict, fout)
-
跃然一笑
import reimport jsonstr = 'a:b# c:d# e:f#' # input stringkv = re.compile("(\w):(\w)") # prepare regular expressionl = kv.findall(str) # find all <key>:<value> pairsd = dict(l) # convert list to dictj = json.dumps(d) # generate JSONprint( d )印刷{'a': 'b', 'c': 'd', 'e': 'f'}