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では、リストとdictを含むリストのように見えるからといって、それが何であるかを意味するわけではありません。Pythonオブジェクトは__repr__、有益な文字列を表示するメソッドを実装していますが、これは誤解を招く場合があります。pyparsingの場合、parseStringメソッドはParseResults型のオブジェクトを返します。ParseResultsは、リストとdictの両方のような動作をする可能性があるため、1つを出力すると、次のタプルが出力されます。

(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

したがって、元の質問に答えるには、リストアクセスセマンティクスを使用して、解析アクションによって返されるdictを取得できる必要があります。

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