1

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

例如:

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

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

谢谢你。

4

2 回答 2

0

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

configGrammar = Grammar(r"""
file = "\n"* line* "\n"*
line = key ws? "=" ws? valueComment (";" valueComment)* "\n"
key = ~"[0-9A-z_]+"
valueComment = ~"[^;\n]*" 
ws = " "*
""")`
于 2016-12-21T09:58:31.210 回答
0

你可以这样做:

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. 
   ...
于 2016-12-21T06:58:22.090 回答