如何在使用pyparsing并将结果作为字典返回时保留类型

时间:2013-08-13 13:22:07

标签: python types dictionary pyparsing

我是pyparsing的新手,希望有人可以帮助我。我试图解析的文本类型具有以下结构:

我在一行中有key = value对,可以有一对或多对。值可以是多种类型,例如string,int,float,list,dictionary。键总是一个字符串。具有4对的行的示例:

  

mode ='clip'clipzeros = True field ='1331 + 0444 = 3C286'clipminmax = [0,1.2]

所以我将语法和解析器定义为:

import pyparsing as pp

key = pp.Word(pp.alphas+"_")
separator = pp. Literal("=").suppress()
value = pp.Word(pp.printables)
pair = key+separator+value

line = pp.OneOrMore(pair)

mytest = "mode='clip' clipzeros=True field='1331+0444=3C286' clipminmax=[0,1.2]"
res = line.parseString(mytest)
print res

它返回:

['mode',''clip'“,'clipzeros','True','field',''1331 + 0444 = 3C286'”,'clipminmax','[0,1.2]']

我希望得到两件事:

  1. 我希望将结果作为字典,例如: {“mode”:“clip”,“clipzeros”:True,“field”:“1331 + 0444 = 3C286”,“clipminmax”:[0,1.2]}

  2. 我想在结果字典中保留值的类型。例如: 值的类型clipzeros是一个布尔值。值clipminmax的类型是一个列表。

  3. 这在pyparsing中是否可行?

    非常感谢您的帮助。

    桑德拉

2 个答案:

答案 0 :(得分:1)

尝试使用eval()来获取您的类型。

import pyparsing as pp

key = pp.Word(pp.alphas+"_")
separator = pp. Literal("=").suppress()
value = pp.Word(pp.printables)
pair = key+separator+value

line = pp.OneOrMore(pair)

mytest = "mode='clip' clipzeros=True field='1331+0444=3C286' clipminmax=[0,1.2]"
res = line.parseString(mytest)
mydict = dict(zip(res[::2],[eval(x) for x in res[1::2]])

收率:

{'field': '1331+0444=3C286', 'mode': 'clip', 'clipzeros': True, 'clipminmax': [0, 1.2]}

另一个例子:

res = ['mode', "'clip'", 'clipzeros', 'True', 'field', "'R RQT'", 'clipminmax', '[0,1.2]']
mydict = dict(zip(res[::2],[eval(x) for x in res[1::2]]))

print mydict

收率:

  {'field': 'R RQT', 'mode': 'clip', 'clipzeros': True, 'clipminmax': [0, 1.2]}

替代pyparser(我没有那个模块):

class Parser():
    def __init__(self,primarydivider,secondarydivider):
        self.prime = primarydivider
        self.second = secondarydivider

    def parse(self,string):
        res = self.initialsplit(string)
        new = []
        for entry in res:
            if self.second not in entry:
                new[-1] += ' ' + entry
            else:
                new.append(entry)
        return dict((entry[0],eval(entry[1])) for entry in [entry.split(self.second) for entry in new])

    def initialsplit(self,string):
        return string.split(self.prime)

mytest = "mode='clip' clipzeros=True field='AEF D' clipminmax=[0,1.2]"
myParser = Parser(' ', '=')
parsed = myParser.parse(mytest)
print parsed

产量

 {'field': 'AEF D', 'mode': 'clip', 'clipzeros': True, 'clipminmax': [0, 1.2]}

OP的评论编辑:

Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> mytest = "mode='clip' clipzeros=True field='R RQT' clipminmax=[0,1.2]"
>>> print mytest
mode='clip' clipzeros=True field='R RQT' clipminmax=[0,1.2]
>>>

答案 1 :(得分:0)

我建议为不同类型的值文字定义特定表达式,而不是像Word(printables)那样使用通用的东西:

from pyparsing import *

# what are the different kinds of values you can get?
int_literal = Combine(Optional('-') + Word(nums))
float_literal = Regex(r'\d+\.\d*')
string_literal = quotedString
bool_literal = Keyword("True") | Keyword("False")
none_literal = Keyword("None")
list_literal = originalTextFor(nestedExpr('[',']'))
dict_literal = originalTextFor(nestedExpr('{','}'))

# define an overall value expression, of the different types of values
value = (float_literal | int_literal | bool_literal | none_literal | 
        string_literal | list_literal | dict_literal)

key = Word(alphas + '_')

def evalValue(tokens):
    import ast
    # ast.literal_eval is safer than global eval()
    return [ast.literal_eval(tokens[0])]
pair = Group(key("key") + '=' + value.setParseAction(evalValue)("value"))

line = OneOrMore(pair)

现在解析你的样本:

sample = """mode='clip' clipzeros=True field='1331+0444=3C286' clipminmax=[0,1.2]"""

result = line.parseString(sample)
for r in result:
    print r.dump()
    print r.key
    print r.value
    print

打印:

['mode', '=', 'clip']
- key: mode
- value: clip
mode
clip

['clipzeros', '=', True]
- key: clipzeros
- value: True
clipzeros
True

['field', '=', '1331+0444=3C286']
- key: field
- value: 1331+0444=3C286
field
1331+0444=3C286

['clipminmax', '=', [0, 1.2]]
- key: clipminmax
- value: [0, 1.2]
clipminmax
[0, 1.2]