How to feed a string in pyparsing line by line?

I came across this question when I want to parse a large file using pyparsing. I have already created pyparsing grammar for the whole file. But I'm not sure how to pass a line to the parser line by line while reading this large file. I am currently using a method like:

pyparsingGrammer = some pyparsing grammar I created PyparsingGrammar.parseString(open(filename).read()) 

With the exception of using memory for large read() , another motivation for me to switch to linear feed is to expand my parser to a real-time case, when information is fed into the parser of one line and then another.

+4
source share
1 answer

You can do:

 with open(filename) as f: for line in f: PyparsingGrammar.parseString(line) 

Using the with keyword automatically closes the file as soon as you are done and gives you a pen to work with.

 for x in something: do_something 

- a standard way to iterate through it (material that can be repeated, for example: list, tuple, dictionary in Python.

I forgot to mention, but I suppose you understood this:
when you open a file in Python with with open(filename) as f , you get list , where each line in the list is an element. That is why you can consider f as an iterator.

+5
source

Source: https://habr.com/ru/post/1436750/


All Articles