【问题标题】:Python Pyparsing: Capture comma-separated list inside parentheses ignoring inner parenthesesPython Pyparsing:在括号内捕获逗号分隔的列表,忽略内括号
【发布时间】:2017-04-02 17:58:29
【问题描述】:

我有一个关于如何正确解析字符串的问题,如下所示,

"(test.function, arr(3,12), "combine,into one")"

进入以下列表,

['test.function', 'arr(3,12)', '"combine,into one"']

注意:原始字符串中的'list'项不一定用逗号和空格分隔,也可以是直接用逗号分隔的两项,例如test.function,arr(3,12).

基本上,我想:

  1. 解析括号中的输入字符串,但不解析内括号。 (因此,nestedExpr() 不能按原样使用)
  2. 里面的项目用逗号分隔,但项目本身可能包含逗号。

而且,我只能使用scanString() 而不能使用parseString()

我在 SO 中进行了一些搜索,找到了 thisthis,但我无法将它们翻译成适合我的问题。

谢谢!

【问题讨论】:

    标签: python regex string parsing pyparsing


    【解决方案1】:

    这应该解决您的嵌套和引用问题:

    sample = """(test.function, arr(3,12),"combine,into one")"""
    
    from pyparsing import (Suppress, removeQuotes, quotedString, originalTextFor, 
        OneOrMore, Word, printables, nestedExpr, delimitedList)
    
    # punctuation and basic elements
    LPAR,RPAR = map(Suppress, "()")
    quotedString.addParseAction(removeQuotes)
    
    # what are the possible values inside the ()'s?
    # - quoted string - anything is allowed inside quotes, match these first
    # - any printable, not containing ',', '(', or ')', with optional nested ()'s
    #   (use originalTextFor helper to extract the original text from the input
    #   string)
    value = (quotedString 
             | originalTextFor(OneOrMore(Word(printables, excludeChars="(),") 
                                         | nestedExpr())))
    
    # define an overall expression, with surrounding ()'s
    expr = LPAR + delimitedList(value) + RPAR
    
    # test against the sample
    print(expr.parseString(sample).asList())
    

    打印:

    ['test.function', 'arr(3,12)', 'combine,into one']
    

    【讨论】:

    • 您好 Paul,感谢您分享此解决方案。这个解决了我的问题。我知道 originalTextFor() 和 nestedExpr(),但从未想过以这种方式实现它们。
    猜你喜欢
    • 2020-11-17
    • 2020-02-21
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 2017-06-01
    • 1970-01-01
    相关资源
    最近更新 更多