1

I'm trying to parse a config file where a the value of an entry may have a comment mark in it. So the rule is only the last comment mark is the divider between the value and the comment.

For example:

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

Can I do that with parsimonious? How can I write a grammar that differentiates the last section after the ; sign?

Thank you.

sophros
  • 14,672
  • 11
  • 46
  • 75
Omer
  • 456
  • 1
  • 3
  • 19

2 Answers2

0

You can do something like this:

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. 
   ...
Nurjan
  • 5,889
  • 5
  • 34
  • 54
  • Of course I can do that. I asked if I can use parsimonious to parse such file. – Omer Dec 21 '16 at 07:41
  • @Omer, Sorry. I misunderstood you. I thought you were struggling with parsing the lines in the config file. As to parsimonious, I think, you can use it. – Nurjan Dec 21 '16 at 07:47
  • I was actually hoping for a non-binary answer :) – Omer Dec 21 '16 at 08:15
0

The best solution I could get from parsimonious was to treat the value and differentiate them when visiting the tree:

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