3

我正在使用 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'}], {})]
4

1 回答 1

7

在 Python 中,仅仅因为某些东西看起来像一个包含列表和字典的列表,并不意味着它就是这样。Python 对象实现了__repr__一种显示信息字符串的方法,但这有时会产生误导。在 pyparsing 的情况下,parseString 方法返回一个 ParseResults 类型的对象。ParseResults 可以同时具有列表和字典的行为,因此当您打印出一个时,它会打印以下元组:

(list of matched tokens, dict of named tokens)

如果您使用列表索引(使用整数或切片表示法),则 ParseResults__getitem__方法将索引到匹配标记的列表中。如果您使用键索引(使用非整数键),则 ParseResults__getitem__方法将使用命名标记的字典上的键来返回与该名称关联的值,而不管位置如何。如果键是一个有效的 Python 标识符,那么您甚至可以使用对象属性访问 - 在这种情况下,ParseResults__getattr__方法也将使用该键来索引命名标记的字典,但有一点不同:在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

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

parseList.append(parser.parseString("monkey")[0])
于 2011-08-12T22:35:24.023 回答