使用 pyparsing 解析 python 中的文本文件

Parsing text file in python using pyparsing

我正在尝试使用 pyparsing 解析以下文本。

acp (SOLO1,
     "solo-100",
     "hi here is the gift"
     "Maximum amount of money, goes",
     430, 90)

jhk (SOLO2,
     "solo-101",
     "hi here goes the wind."
     "and, they go beyond",
     1000, 320)

我已经尝试了以下代码,但它不起作用。

flag = Word(alphas+nums+'_'+'-')
enclosed = Forward()
nestedBrackets = nestedExpr('(', ')', content=enclosed)
enclosed << (flag | nestedBrackets)

print list(enclosed.searchString (str1))

引文中的逗号 (,) 产生了不良结果。

好吧,我的评论可能过于简单化了 - 这里有一个更完整的 回答。

如果你真的不需要处理嵌套数据项,那么单级括号 每个部分中的数据组将如下所示:

LPAR,RPAR = map(Suppress, "()")
ident = Word(alphas, alphanums + "-_")
integer = Word(nums)

# treat consecutive quoted strings as one combined string
quoted_string = OneOrMore(quotedString)
# add parse action to concatenate multiple adjacent quoted strings
quoted_string.setParseAction(lambda t: '"' + 
                            ''.join(map(lambda s:s.strip('"\''),t)) + 
                            '"' if len(t)>1 else t[0])
data_item = ident | integer | quoted_string

# section defined with no nesting
section = ident + Group(LPAR + delimitedList(data_item) + RPAR)

我不确定你是否有意省略逗号 两个连续的引用字符串,所以我选择实现像 Python 的编译器这样的逻辑, 其中两个带引号的字符串仅被视为一个较长的字符串,即 "AB CD " "EF" 是 与 "AB CD EF" 相同。这是通过 quoted_string 的定义完成的,并添加 quoted_string 的解析操作以连接 2 个或更多组件的内容 带引号的字符串。

最后,我们为整个组创建一个解析器

results = OneOrMore(Group(section)).parseString(source)
results.pprint()

并从您发布的输入示例中获取:

[['acp',
  ['SOLO1',
   '"solo-100"',
   '"hi here is the giftMaximum amount of money, goes"',
   '430',
   '90']],
 ['jhk',
  ['SOLO2',
   '"solo-101"',
   '"hi here goes the wind.and, they go beyond"',
   '1000',
   '320']]]

如果您有嵌套的括号组,那么您的部分定义可以是 就这么简单:

# section defined with nesting
section = ident + nestedExpr()

尽管正如您已经发现的那样,这将保留单独的逗号,就好像它们一样 是重要的标记,而不仅仅是数据分隔符。