从包含一个或多个标记的字符串构建字典

building a dictionary from a string containing one or more tokens

给出

import pyparsing as pp

lines = '''\
(xcoord -23899.747)
(ycoord 14349.544)
(elev 23899)
(region "mountainous")
(rate multiple)'''

leftParen    = pp.Literal('(')
rightParen   = pp.Literal(')')
doublequote  = pp.Literal('"')
v_string = pp.Word(pp.alphanums)
v_quoted_string = pp.Combine( doublequote + v_string + doublequote)
v_number = pp.Word(pp.nums+'.'+'-')

keyy = v_string
valu = v_string | v_quoted_string | v_number

item  = pp.Group( pp.Literal('(').suppress() + keyy + valu + pp.Literal(')').suppress() 
items = pp.ZeroOrMore( item)
dicct = pp.Dict( items)

pp.ParserElement.setDefaultWhitespaceChars('\r\n\t ')
print "item yields: " ,   item.parseString( lines).dump()
print "items yields: " , items.parseString( lines).dump()
print "dicct yields: ",  dicct.parseString( lines).dump()

给予

item yields: [['xcoord', '-23899.747']]
[0]:['xcoord', '-23899.747']
items yields: [['xcoord', '-23899.747']]
[0]:['xcoord', '-23899.747']
dicct yields: [['xcoord', '-23899.747']]
[0]:['xcoord', '-23899.747']

嗯。我希望在 dicct 中看到五个项目。我对 Dict、ZeroOrMore 和 Group 的使用似乎与网络上的其他示例一致。似乎只有第一项匹配。我做错了什么?

TIA,

代码战士

这比您想象的要容易。 (我们中的一些人只需要几周的练习。)

  • v_number 表示数值,v_string 表示不带引号的字符串值非常简单。
  • 我对带引号的字符串使用了 Combine,以便引号包含在解析结果中的字符串中。
  • 我将 Groupkeyvalue 一起使用,以便这些值在解析器的输出中配对。
  • ZeroOrMore 允许任意数量的 key-value 对,包括零对。

lines = '''\
(xcoord -23899.747)
(ycoord 14349.544)
(elev 23899)
(region "mountainous")
(rate multiple)'''


import pyparsing as pp
key = pp.Word(pp.alphas)
v_number = pp.Word(pp.nums+'.'+'-')
v_string = pp.Word(pp.alphas)
v_quoted_string = pp.Combine(pp.Literal('"') + v_string + pp.Literal('"') )
value = v_number | v_string | v_quoted_string 
item = pp.Literal('(').suppress() + pp.Group(key + value) + pp.Literal(')').suppress() 
collection = pp.ZeroOrMore(item)

result = {}
for item in collection.parseString(lines):
    result[item[0]] = item[1]

for key in result:
    print (key, result[key])

输出:

xcoord -23899.747
ycoord 14349.544
elev 23899
region "mountainous"
rate multiple