python3 中字符串的类似字典的操作
Dictionary like operations on string in python3
我有一个字符串 product: Netatalk version: 2.2.0 extrainfo: name: WNDR4500; protocol 3.3 ostype: Unix
,我希望能够在其中进行类似字典的操作,以获取产品、版本等信息。执行此类操作的最佳方法是什么?我知道我可以用拆分和类似的东西来解决这个问题,但这确实不是 "beautiful" 编码方式。有什么建议吗?
我试着写了一个递归的字典解析器,它一直在折磨我,直到我想 你知道,如果我向后做这个会容易得多... 瞧!
import re
def make_dict(s):
# break into list of keys and values
chunks = re.split("\s*(\w+\:)\s*", s)
res = {}
# work backwards in value,key pairs
args = [reversed(chunks)] * 2
for value,key in zip(*args):
key = key.rstrip(':')
if value:
# add to current result-dict
res[key] = value
else:
# start a higher-level result-dict
res = {key: res}
return res
然后
>>> make_dict("product: Netatalk version: 2.2.0 extrainfo: name: WNDR4500; protocol 3.3 ostype: Unix")
{'extrainfo': {'ostype': 'Unix', 'name': 'WNDR4500; protocol 3.3'},
'version': '2.2.0',
'product': 'Netatalk'}
我自己解决了:
def product(banner):
if banner:
p=re.search('(product:).([^\s]+)', banner)
return p.group(2)
else:
return "unknown"
这将 return "product",如果我需要其他东西,可以进行调整。
我有一个字符串 product: Netatalk version: 2.2.0 extrainfo: name: WNDR4500; protocol 3.3 ostype: Unix
,我希望能够在其中进行类似字典的操作,以获取产品、版本等信息。执行此类操作的最佳方法是什么?我知道我可以用拆分和类似的东西来解决这个问题,但这确实不是 "beautiful" 编码方式。有什么建议吗?
我试着写了一个递归的字典解析器,它一直在折磨我,直到我想 你知道,如果我向后做这个会容易得多... 瞧!
import re
def make_dict(s):
# break into list of keys and values
chunks = re.split("\s*(\w+\:)\s*", s)
res = {}
# work backwards in value,key pairs
args = [reversed(chunks)] * 2
for value,key in zip(*args):
key = key.rstrip(':')
if value:
# add to current result-dict
res[key] = value
else:
# start a higher-level result-dict
res = {key: res}
return res
然后
>>> make_dict("product: Netatalk version: 2.2.0 extrainfo: name: WNDR4500; protocol 3.3 ostype: Unix")
{'extrainfo': {'ostype': 'Unix', 'name': 'WNDR4500; protocol 3.3'},
'version': '2.2.0',
'product': 'Netatalk'}
我自己解决了:
def product(banner):
if banner:
p=re.search('(product:).([^\s]+)', banner)
return p.group(2)
else:
return "unknown"
这将 return "product",如果我需要其他东西,可以进行调整。