编程语言
首页 > 编程语言> > python – 词典和pyparsing列表

python – 词典和pyparsing列表

作者:互联网

我正在使用pyparsing来构建附加到列表的字典.当我这样做时,字典被包含在一个额外的列表中,并且还附加了一个空的字典.我不知道如何解决这个问题.我想要的是[{},{},{}].我得到[([{}],{})]为什么getDict的代码给了我想要的东西而不是getDictParse?

#! /usr/bin/env python
from pyparsing import Literal, NotAny, Word, printables, Optional, Each, Combine, delimitedList, printables, alphanums, nums, White, OneOrMore, Group

noParseList = []
parseList   = []

def getDict():
    return {'duck':'moose','cow':'ewe'}

def getDictParse(str, loc, toks):
    return {'duck2':toks[0],'cow2':'ewe'}

parser = Word(alphanums)
parser.setParseAction(getDictParse)
parseList.append(parser.parseString("monkey"))

noParseList.append(getDict())

print noParseList
print parseList

输出:

[{'cow': 'ewe', 'duck': 'moose'}]
[([{'cow2': 'ewe', 'duck2': 'monkey'}], {})]

解决方法:

在Python中,仅仅因为看起来像包含列表和字典的列表,并不意味着它就是它的本质. Python对象实现了一个__repr__方法,该方法将显示信息性字符串,但这有时会产生误导.在pyparsing的情况下,parseString方法返回ParseResults类型的对象. ParseResults可以有类似list和dicts的行为,所以当你打印出一个时,它会打印这个元组:

(list of matched tokens, dict of named tokens)

如果使用列表索引(使用整数或切片表示法),则ParseResults __getitem__方法将索引到匹配的标记列表中.如果使用键索引(使用非整数键),ParseResults __getitem__方法将使用命名标记的dict上的键返回与该名称关联的值,而不管位置如何.如果密钥是一个有效的Python标识符,那么你甚至可以使用对象属性访问 – 在这种情况下,ParseResults __getattr__方法也将使用该键来索引命名标记的dict,但有所不同:如果是一个KeyError,使用对象属性语法会给你一个空字符串”.这是一个更详细的示例,请按照注释说明不同的选项:

from pyparsing import *

# define an integer token, and a parse-time conversion function
def cvtInteger(tokens):
    return int(tokens[0])
integer = Word(nums).setParseAction(cvtInteger)

# define an animal type, with optional plural 's'
animal = Combine(oneOf("dog cat monkey duck llama") + Optional("s"))

# define an expression for some number of animals
# assign results names 'qty' and 'animal' for named access
# to parsed data tokens
inventoryItem = integer("qty") + animal("animal")

# some test cases
items = """\
    7 llamas
    1 duck
    3 dogs
    14 monkeys""".splitlines()

for item in items:
    info = inventoryItem.parseString(item)
    # print the parsed item
    print type(info), repr(info)

    # use string key to access dict item
    print info['qty']

    # use object attribute to access dict item
    print info.animal

    # use list indexing to access items in list
    print info[-1]

    # use object attribute to access
    print info.average_weight

打印:

<class 'pyparsing.ParseResults'> ([7, 'llamas'], {'animal': [('llamas', 1)], 'qty': [(7, 0)]})
7
llamas
llamas

<class 'pyparsing.ParseResults'> ([1, 'duck'], {'animal': [('duck', 1)], 'qty': [(1, 0)]})
1
duck
duck

<class 'pyparsing.ParseResults'> ([3, 'dogs'], {'animal': [('dogs', 1)], 'qty': [(3, 0)]})
3
dogs
dogs

<class 'pyparsing.ParseResults'> ([14, 'monkeys'], {'animal': [('monkeys', 1)], 'qty': [(14, 0)]})
14
monkeys
monkeys

因此,要回答原始问题,您应该能够使用列表访问语义来获取解析操作返回的字典:

parseList.append(parser.parseString("monkey")[0])

标签:pyparsing,python
来源: https://codeday.me/bug/20190903/1795246.html