【问题标题】:python parsimonious: Parsing config file with multiple comment markspython parsimonious:解析具有多个注释标记的配置文件
【发布时间】:2016-12-21 06:47:34
【问题描述】:

我正在尝试解析一个配置文件,其中条目的值可能包含注释标记。所以规则只有最后一个注释标记是值和注释之间的分隔符。

例如:

key1 = value
key2 = value;This is a comment
key3 = value;This is still value;This is a comment

我可以简约做到这一点吗?如何编写区分; 符号后最后一部分的语法?

谢谢。

【问题讨论】:

    标签: python parsing config peg parsimonious


    【解决方案1】:

    你可以这样做:

    with open('config_file') as f:
        content = f.readlines()
    
    for c in content:
       tmp = c.split(';') # Split line by `;`.
       comment = tmp[len(tmp) - 1]  # This is the comment part. 
       ...
    

    【讨论】:

    • 当然可以。我问我是否可以使用 parsimonious 来解析这样的文件。
    • @Omer,对不起。我误解了你。我以为您正在努力解析配置文件中的行。至于简约,我想,你可以用它。
    • 我实际上希望得到一个非二进制的答案:)
    【解决方案2】:

    我可以从简约中得到的最佳解决方案是在访问树时处理值并区分它们:

    configGrammar = Grammar(r"""
    file = "\n"* line* "\n"*
    line = key ws? "=" ws? valueComment (";" valueComment)* "\n"
    key = ~"[0-9A-z_]+"
    valueComment = ~"[^;\n]*" 
    ws = " "*
    """)`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-20
      • 2017-06-25
      • 2023-03-11
      • 2011-04-16
      • 1970-01-01
      • 2014-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多