Pyparser如何解析相似的定界和非定界字符串

2024-06-25 06:47:06 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用两个单独的解析器来解析下面的两种类型的字符串-每个模式一个?在

from pyparsing import *    
dd = """
  wire         c_f_g;
  wire         cl_3_f_g4;

   x_y abc_d
      (.c_l (cl_dclk_001l),
       .c_h (cl_m1dh_ff),
       .ck     (b_f_1g));

我可以使用下面的解析器独立解析它们(分别):

^{pr2}$

如果运行上述代码,instanceStart解析器将与连线匹配。我怎样才能可靠地区分这两者呢?在


Tags: 字符串fromimport解析器类型cl模式pyparsing
1条回答
网友
1楼 · 发布于 2024-06-25 06:47:06

我有一个有效的解决方案(绝对不是最好的)。在

    printables_less_semicolon = printables.replace(';','')

bracketStuff    = Group(QuotedString("(", escChar=None, multiline=True, endQuoteChar=");"))
ifDef           = Group(QuotedString("`ifdef", endQuoteChar="`endif", multiline=True))
theEnd          = Word( "endmodule" )
nestedConns     = Group(nestedExpr(opener="(", closer=")", ignoreExpr=dblSlashComment))
instance        = Regex('[\s?|\r\n?].*\(')
othersWithSc    = Group(Word (printables) + Word (printables_less_semicolon) + Literal(";"))
othersWithoutSc = Word (printables) + Word (printables_less_semicolon) + NotAny(Literal(";"))

以上解析器的组合允许我以我正在处理的格式解析文件。 输入示例:

^{pr2}$

用于解析上述内容的解析器:

try:
    tp  = othersWithoutSc + Optional(bracketStuff) + Optional(ZeroOrMore(othersWithSc)) + Optional( Group( ZeroOrMore( othersWithoutSc + nestedConns ) ) ) + theEnd
    tpI = Group( ZeroOrMore( othersWithoutSc + nestedConns +  Word( ";" ) ) )
    tpO = Each( [Optional(ZeroOrMore(othersWithSc)), Optional(ifDef)] )
    tp  = othersWithoutSc + Optional(bracketStuff) + tpO + Group(tpI) + theEnd
    #print othersWithoutSc.parseString("input xyz;")
    print tp.parseString(ts2)
except ParseException as x:
    print "Line {e.lineno}, column {e.col}:\n'{e.line}'".format(e=x)

获得的输出:

module
storyOfFox
[' andDog, \n        JLT']
['input', 'andDog', ';']
['output', 'JLT', ';']
[' quickFox\n `include "gatorade"\n `include "chicken" \n']
['wire', 'hello', ';']
['wire', 'and', ';']
['wire', 'welcome', ';']
[['the', 'quick', [['.brown', ['fox'], ',', '.jumps', ['over'], ',', '.the', ['lazy'], ',', '.dog', ['and'], ',', '.the', ['dog'], ',', '.didNot', ['likeIt']]], ';', 'theDog', 'thenWent', [['// Waiver unused', '.on', [], ',', '// Waiver unused', '.to', [], ',', '.sueThe', ['foxFor'], ',', '.jumping', ['andBeingTooQuick'], ',', '.TheDog', ['wasHailedAsAHero'], ',', '.endOf', ['Story']]], ';']]
endmodule

我现在还不想接受这个答案,因为我可能还没有解决我以前面临的真正问题。我只是想办法绕过它,得到我需要的输出。在

相关问题 更多 >