根据 Paul(pyparsing 的作者)
with open('file_name') as f:
for line in f:
PyGrammar.parseString(line)
上面的代码不是使用 pyparsing 的正确方法。Pyparsing 需要在解析文本之前查看所有源文本。所以当我用每一行文本调用 parseString 时,它不起作用。另一种解决方法是为其使用包装器。喜欢:
# set up a generator to yield a line of text at a time
linegenerator = open('big_hairy_file.txt')
# buffer will accumulate lines until a fully parseable piece is found
buffer = ""
for line in linegenerator:
buffer += line
match = next(grammar.scanString(buffer), None)
while match:
tokens, start, end = match
print tokens.asList()
buffer = buffer[end:]
match = next(grammar.scanString(buffer), None)