Python:以最优雅的方式拆分此长度结构化的字符串 [英] Python: split this length-structured string the most elegant way

查看:90
本文介绍了Python:以最优雅的方式拆分此长度结构化的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下字符串:

fsw="M525x617M525x617S16d48492x577S10000505x544S22a00506x524S21300487x601S37601511x574S34500482x483

我想转换

fsw[8:] (thus "M525x617S16d48492x577S10000505x544S22a00506x524S21300487x601S37601511x574S34500482x483")

在包含以下内容的字典中

in a dictionary containing:

{'S16d48':'492x577', 'S10000':'505x544', 'S22a00':'506x524', 'S21300':'487x601', 'S37601':'511x574', 'S34500':'482x483'}

我设法通过regexp获得了以下内容:

I managed to get the following with regexp:

>>> import re
>>> re.findall("S[123][0-9a-f]{2}[0-5][0-9a-f]",fsw[8:])
['S16d48', 'S10000', 'S22a00', 'S21300', 'S37601', 'S34500']

>>> re.findall("S[123][0-9a-f]{2}[0-5][0-9a-f].......",fsw[8:])
['S16d48492x577', 'S10000505x544', 'S22a00506x524', 'S21300487x601', 'S37601511x574', 'S34500482x483']

但就字典而言...我无法再进一步了.

but as far as a dictionary is concerned... I failed to get any further.

另一个问题:在Python字典中,整体来说还不错 键值对(例如"S16d48":"492x577")必须是唯一的对吗?

Another question: in a Python dictionary it is well the whole key-value pair (say "S16d48":"492x577") that must be unique right ?

提前-非常感谢. 问候.

In advance - thanks a lot. Regards.

推荐答案

似乎您可以将表达式更改为

It seems you can alter your expression to

(?P<key>S[123][0-9a-f]{2}[0-5][0-9a-f])
(?P<value>\d+x\d+)

然后像

import re
rx = re.compile(r'(?P<key>S[123][0-9a-f]{2}[0-5][0-9a-f])(?P<value>\d+x\d+)')

data = "M525x617M525x617S16d48492x577S10000505x544S22a00506x524S21300487x601S37601511x574S34500482x483"

result = {m["key"]: m["value"] for m in rx.finditer(data)}

这产生

{'S16d48': '492x577', 'S10000': '505x544', 'S22a00': '506x524', 'S21300': '487x601', 'S37601': '511x574', 'S34500': '482x483'}


在regex101.com上看到演示 的演示 ideone.com 上的代码.


See a demo for the expression on regex101.com and for the code on ideone.com.

这篇关于Python:以最优雅的方式拆分此长度结构化的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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