Skip to main content
 首页 » 编程设计

python之优雅的解析这个 "a,b,c",d ,"e,f"

2025年05月04日10soundcode

我希望将这些类型的字符串解析为 Python 中的列表:

"a,b,c",d,"e,f"        =>  ['a','b','c'] , ['d'] , ['e','f'] 
"a,b,c",d,e            =>  ['a','b','c'] , ['d'] , ['e'] 
a,b,"c,d,e,f"          =>  ['a'],['b'],['c','d','e','f'] 
a,"b,c,d",{x(a,b,c-d)} =>  ['a'],['b','c','d'],[('x',['a'],['b'],['c-d'])] 

它嵌套,所以我怀疑正则表达式已经过时了。我所能想到的就是开始计算引号和括号来解析它,但这似乎非常不雅。或者也许首先匹配引号并用 somechar 替换它们之间的逗号,然后按逗号拆分,直到完成所有嵌套,最后在 somechar 上重新拆分。

有什么想法吗?

请您参考如下方法:

所以,这就是您的“诚实的 Python 解析器”。为您编码而不是回答问题,但如果您使用它我会很好:-)

QUOTE = '"' 
SEP = ',(){}"' 
S_BRACKET = '{' 
E_BRACKET = '}' 
S_PAREN = '(' 
 
def parse_plain(string): 
    counter = 0 
    token = "" 
    while counter<len(string): 
        if string[counter] in SEP: 
            counter += 1 
            break 
        token += string[counter] 
        counter += 1 
    return counter, token 
 
def parse_bracket(string): 
    counter = 1 
    fwd, token = parse_plain(string[counter:]) 
    output = [token] 
    counter += fwd 
    fwd, token = parse_(string[counter:]) 
    output += token 
    counter += fwd 
    output = [tuple(output)] 
    return counter, output 
 
def parse_quote(string): 
    counter = 1 
    output = [] 
    while counter<len(string): 
        if counter > 1 and string[counter - 1] == QUOTE: 
            counter += 1 
            break 
        fwd, token = parse_plain(string[counter:]) 
        output.append(token) 
        counter += fwd 
    return counter, output 
 
def parse_(string): 
    output = [] 
    counter = 0 
    while counter < len(string): 
        if string[counter].isalpha(): 
            fwd, token = parse_plain(string[counter:]) 
            token = [token] 
        elif string[counter] == QUOTE: 
            fwd, token = parse_quote(string[counter:]) 
        elif string[counter] == S_BRACKET: 
            fwd, token = parse_bracket(string[counter:]) 
        elif string[counter] == E_BRACKET: 
            counter += 1 
            break 
        else: 
            counter += 1 
            continue 
        output.append(token) 
        counter += fwd 
    return counter, output 
 
def parse(string): 
    return parse_(string)[1] 

并测试输出:

>>> print parse('''"a,b,c",d,"e,f"''') 
[['a', 'b', 'c'], ['d'], ['e', 'f']] 
>>> print parse('''"a,b,c",d,e ''') 
[['a', 'b', 'c'], ['d'], ['e ']] 
>>> print parse('''a,b,"c,d,e,f"''') 
[['a'], ['b'], ['c', 'd', 'e', 'f']] 
>>> print parse('''a,"b,c,d",{x(a,b,c-d)}''') 
[['a'], ['b', 'c', 'd'], [('x', ['a'], ['b'], ['c-d'])]] 
>>> print parse('''{x(a,{y("b,c,d",e)})},z''') 
[[('x', ['a'], [('y', ['b', 'c', 'd'], ['e'], ['z'])])]] 
>>>