Python中使用pyparsing来解析文本文件

2024-06-01 06:21:09 发布

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

我尝试使用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)

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

^{pr2}$

引号中的逗号(,)产生了不希望的结果。在


Tags: ofthe文本hereispyparsinghiamount
1条回答
网友
1楼 · 发布于 2024-06-01 06:21:09

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

如果不需要处理嵌套的数据项,则使用一个单级括号 每个部分中的数据组如下所示:

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"相同。这是用带引号的字符串的定义完成的,并添加 将两个或多个组件的内容连在一起的带引号的字符串的解析操作 带引号的字符串。在

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

^{pr2}$

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

[['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']]]

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

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

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

相关问题 更多 >