Dam*_*ian 2 python parsing pyparsing
我需要解析一个文件,其中包含用大括号分隔的信息,例如:
Continent
{
Name Europe
Country
{
Name UK
Dog
{
Name Fiffi
Colour Gray
}
Dog
{
Name Smut
Colour Black
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我在Python中尝试过的
from io import open
from pyparsing import *
import pprint
def parse(s):
return nestedExpr('{','}').parseString(s).asList()
def test(strng):
print strng
try:
cfgFile = file(strng)
cfgData = "".join( cfgFile.readlines() )
list = parse( cfgData )
pp = pprint.PrettyPrinter(2)
pp.pprint(list)
except ParseException, err:
print err.line
print " "*(err.column-1) + "^"
print err
cfgFile.close()
print
return list
if __name__ == '__main__':
test('testfile')
Run Code Online (Sandbox Code Playgroud)
但这失败了,出现了错误:
testfile
Continent
^
Expected "{" (at char 0), (line:1, col:1)
Traceback (most recent call last):
File "xxx.py", line 55, in <module>
test('testfile')
File "xxx.py", line 40, in test
return list
UnboundLocalError: local variable 'list' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
我需要做些什么来完成这项工作?另一种解析器比pyparsing更好吗?
嵌套表达式非常常见,如果您不使用解析库,通常需要递归解析器定义或递归代码.这段代码对于初学者来说可能是令人生畏的,即使对于专家来说也容易出错,所以这就是为什么我将nestedExpr帮助器添加到pyparsing中.
您遇到的问题是您的输入字符串不仅仅包含嵌套的大括号表达式.当我第一次尝试解析器时,我尽量保持测试的简单性 - 例如,我内联样本而不是从文件中读取它.
test = """\
Continent
{
Name Europe
Country
{
Name UK
Dog
{
Name Fiffi
Colour "light Gray"
}
Dog
{
Name Smut
Colour Black
}}}"""
from pyparsing import *
expr = nestedExpr('{','}')
print expr.parseString(test).asList()
Run Code Online (Sandbox Code Playgroud)
我得到了与您相同的解析错误:
Traceback (most recent call last):
File "nb.py", line 25, in <module>
print expr.parseString(test).asList()
File "c:\python26\lib\site-packages\pyparsing-1.5.7-py2.6.egg\pyparsing.py", line 1006, in parseString
raise exc
pyparsing.ParseException: Expected "{" (at char 1), (line:1, col:1)
Run Code Online (Sandbox Code Playgroud)
因此,查看错误消息(甚至在您自己的调试代码中),pyparsing在主要单词"Continent"上磕磕绊绊,因为这个单词不是大括号中的嵌套表达式的开头,pyparsing(正如我们在异常消息中看到的那样) )正在寻找一个开头'{'.
解决方案是稍微修改您的解析器以处理介绍性的"Continent"标签,方法是将expr更改为:
expr = Word(alphas) + nestedExpr('{','}')
Run Code Online (Sandbox Code Playgroud)
现在,将结果打印出来作为列表(使用pprint,如在OP中所做的那样,做得很好)看起来像:
['Continent',
['Name',
'Europe',
'Country',
['Name',
'UK',
'Dog',
['Name', 'Fiffi', 'Colour', '"light Gray"'],
'Dog',
['Name', 'Smut', 'Colour', 'Black']]]]
Run Code Online (Sandbox Code Playgroud)
这应该与你的支架嵌套相匹配.