【问题标题】:How do I select information from a given block using pyparsing?如何使用 pyparsing 从给定块中选择信息?
【发布时间】:2021-01-14 06:39:14
【问题描述】:

我需要从特定区块获取信息,为什么遇到关键字就不能停止分析?

source_string = '''

Code: 49662 (ACTIVE)
****************** Source: ******************
Key: Value
Description: test description 1
Key: Value
****************** Base information ******************
Key: Value
Description: test description 2
Key: Value
****************** Additional information ******************
Key: Value
Description: test description 3
Key: Value

'''

grammar = pp.Combine(pp.OneOrMore( \
    pp.CaselessLiteral('Code') + pp.Optional(':') + pp.restOfLine() \
    + pp.SkipTo(pp.CaselessLiteral('Base information')).suppress() \
    ^ pp.CaselessLiteral('Description') + pp.restOfLine() \
    , stopOn = pp.CaselessLiteral('Additional information')
))
pprint(grammar.searchString(source_string).asList())

结果:

[['代码:49662(活动)'], ['描述:测试描述 2'], ['描述:测试描述3']]

我使用SkipTo()排除的“测试描述1”的第一个值,如何从结果中排除“测试描述3”?

【问题讨论】:

    标签: python python-3.x python-2.7 parsing pyparsing


    【解决方案1】:

    这解决了我的问题

    source_string = '''
    
    Code: 49662 (ACTIVE)
    ****************** Source: ******************
    Key: Value
    Description: test description 1
    Key: Value
    Source: ip adress1
    ****************** Base information ******************
    Source: ip adress
    Key: Value
    Description: test description 2
    
    Key: Value
    ****************** Additional information ******************
    Key: Value
    Description: test description 3
    Key: Value
    Source: ip adress3
    '''
    
    grammar = pp.CaselessLiteral('Code') + pp.restOfLine() \
        ^ pp.Combine(pp.CaselessLiteral('Base information') + pp.restOfLine()).suppress() \
            + pp.OneOrMore(
                pp.Combine(pp.CaselessLiteral('Description') + pp.restOfLine()) \
                ^ pp.Combine(pp.CaselessLiteral('Source') + pp.restOfLine()) \
                ^ pp.Word(pp.printables).suppress()
                , stopOn = '*'
            )
    
    
    pprint(grammar.searchString(source_string).asList())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多