簡體   English   中英

簡單的嵌套表達式與pyparsing匹配

[英]Simple nested expression matching with pyparsing

我想匹配一個看起來像這樣的表達式:

(<some value with spaces and m$1124any crazy signs> (<more values>) <even more>)

我只想沿方括號()拆分這些值。 目前,我可以減少s-expression示例中的pyparsing開銷,因為這是廣泛且難以理解的 (IMHO)。

我可以使用nestedExpr語句,將其減少為一行:

import pyparsing as pp
parser = pp.nestedExpr(opener='(', closer=')')
print parser.parseString(example, parseAll=True).asList()

結果也似乎在空白處被分割,我不希望這樣做:

  skewed_output = [['<some',
  'value',
  'with',
  'spaces',
  'and',
  'm$1124any',
  'crazy',
  'signs>',
  ['<more', 'values>'],
  '<even',
  'more>']]
expected_output = [['<some value with spaces and m$1124any crazy signs>' 
['<more values>'], '<even more>']]
best_output = [['some value with spaces and m$1124any crazy signs' 
['more vlaues'], 'even more']]

可選地,我很樂意在任何地方都可以讀到一些易於理解的介紹,例如如何包括更詳細的解析器(我想提取<>括號之間的值並將其匹配(請參閱best_output ),但是我可以之后總是將它們string.strip()

提前致謝!

Pyparsing的nestedExpr接受contentignoreExpr參數,這些參數指定什么是s-expr的“單個項目”。 您可以在此處傳遞QuotedString 不幸的是,我對文檔中兩個參數之間的區別還不夠了解,但是一些實驗表明,以下代碼應滿足您的要求:

import pyparsing as pp

single_value = pp.QuotedString(quoteChar="<", endQuoteChar=">")
parser = pp.nestedExpr(opener="(", closer=")",
                       content=single_value,
                       ignoreExpr=None)

example = "(<some value with spaces and m$1124any crazy signs> (<more values>) <even more>)"
print(parser.parseString(example, parseAll=True))

輸出:

[['some value with spaces and m$1124any crazy signs', ['more values'], 'even more']]

它期望列表以( ,以)結尾,並包含一些可選的用空格分隔的列表或帶引號的字符串,每個帶引號的字符串應以<開頭,以>結束並且不包含<內部。

您可以更多地使用contentignoreExpr參數來發現content=None, ignoreExpr=single_value使content=None, ignoreExpr=single_value接受帶引號和不帶引號的字符串(以及帶空格的不帶引號的字符串):

import pyparsing as pp

single_value = pp.QuotedString(quoteChar="<", endQuoteChar=">")
parser = pp.nestedExpr(opener="(", closer=")", ignoreExpr=single_value, content=None)

example = "(<some value with spaces and m$1124any crazy signs> (<more values>) <even m<<ore> foo (foo) <(foo)>)"
print(parser.parseString(example, parseAll=True))

輸出:

[['some value with spaces and m$1124any crazy signs', ['more values'], 'even m<<ore', 'foo', ['foo'], '(foo)']]

一些問題懸而未決:

  1. 為什么pyparsing會忽略連續列表項之間的空格?
  2. contentignoreExpr什么區別,什么時候應該使用它們?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM