2013-05-03 106 views
4

欣赏单行代码方面的帮助,以便高效地执行以下操作。拆分python中的大括号分组字符串

我有通过下面括号分离群体的字符串:

{1:xxxx}{2:xxxx}{3:{10:xxxx}}{4:xxxx\r\n:xxxx}.... 

如何转换到这个字典格式?

dict={1:'xxx',2:'xxxx',3:'{10:xxxx}'},4:'xxxx\r\n:xxxx'} 
+0

'xxxx's是否包含大括号? – unutbu 2013-05-03 10:07:20

+1

好问题。他们这样做 - 并已编辑类似的问题 – IUnknown 2013-05-03 10:09:01

+1

“值”是随机引用/未引用? – root 2013-05-03 10:15:15

回答

0

这是我会怎么做:

raw = """{1:xxxx}{2:xxxx}{3:{10:xxxx}}{4:'xxxx\r\n:xxxx'}""" 

def parse(raw): 
    # split into chunks by '}{' and remove the outer '{}' 
    parts = raw[1:-1].split('}{') 
    for part in parts: 
     # split by the first ':' 
     num, data = part.split(':', 1) 
     # yield each entry found 
     yield int(num), data 

# make a dict from it 
print dict(parse(raw)) 

它将'{10:xxxx}'保存为一个字符串,就像您的示例中一样。

4
r = """(?x) 
{ 
    (\w+) 
    : 
    (
     (?: 
      [^{}] 
      | 
      {.+?} 
     )+ 
    ) 
} 
""" 

z = "{1:xxxx}{2:xxxx}{3:{10:xxxx}}{4:'xxxx'}" 
print dict(re.findall(r, z)) 

# {'1': 'xxxx', '3': '{10:xxxx}', '2': 'xxxx', '4': "'xxxx'"} 

随意转换成一个班轮如果你想 - 只是删除(?x)和正则表达式的所有空格。

上述解析嵌套的只有一个级别,处理任意深度的考虑更先进regex模块,它支持递归模式:

import regex 

r = """(?x) 
{ 
    (\w+) 
    : 
    (
     (?: 
      [^{}] 
      | 
      (?R) 
     )+ 
    ) 
} 
""" 

z = "{1:abc}{2:{3:{4:foo}}}{5:bar}" 
print dict(regex.findall(r, z)) 

# {'1': 'abc', '2': '{3:{4:foo}}', '5': 'bar'} 
+0

我喜欢这样,但是如果在输入字符串中嵌套了'{}',比如'{3:{10:{}}}',那么它会失败 - 您将返回'[('3', '{10:{}')]'。 – 2013-05-03 10:36:27