python - 使用 pyparsing 在 python 中解析文本文件

标签 python 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()

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

关于python - 使用 pyparsing 在 python 中解析文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31730362/

相关文章:

python - pyparsing如何从字符串创建语法对象

python - 如何在解析过程中丢弃 pyparsing parseResults?

python - imageio-值错误: Could not find a format to read the specified file in mode 'i'

python - 使用python将变量传递给bash命令

python - 旋转列表列表

python - 每次鼠标移到kivy中的小部件上时,如何打印指针的位置?

Python 临时文件 [Errno 66] 目录不为空

python - 有选择地替换字符串中特定的嵌套定界符(括号),同时尊重嵌套

python - 解析嵌套的三元表达式

python - pyparsing 访问 ParseResults 时遇到问题