基于逆向分隔符匹配规则的字符串转Python字典解析需求
解析特定格式字符串为Python字典
示例
输入
aaa_bbb_ /xyz=uvw,ccc=height:18y,weight:1xb,ddd=19d
输出
{'aaa_bbb_ /xyz': 'uvw', 'ccc': 'height:18y,weight:1xb', 'ddd': '19d'}
解析规则
- 从右往左定位第一个
=,将其右侧内容作为value - 在该
=的左侧子串中,继续从右往左定位第一个,,,与=之间的内容作为key - 移除已解析的
,key=value片段后,对剩余字符串重复上述操作 - 输入字符串至少包含一组键值对,值允许包含
,及多数特殊字符
实现代码
def parse_special_string(input_str): parsed_dict = {} remaining = input_str.strip() while remaining: # 从右找第一个等号,拆分出值 eq_pos = remaining.rfind('=') value = remaining[eq_pos + 1:] # 在等号左侧找最后一个逗号,拆分出键 comma_pos = remaining[:eq_pos].rfind(',') if comma_pos == -1: # 没有逗号,左侧全部为键 key = remaining[:eq_pos] remaining = '' else: key = remaining[comma_pos + 1:eq_pos] remaining = remaining[:comma_pos] parsed_dict[key] = value # 反转键的顺序以匹配示例输出(Python 3.7+字典保留插入顺序) return dict(reversed(parsed_dict.items())) # 测试示例 test_input = "aaa_bbb_ /xyz=uvw,ccc=height:18y,weight:1xb,ddd=19d" print(parse_special_string(test_input))
运行上述代码后,输出将与示例完全一致。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

