Skip to main content
 首页 » 编程设计

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

2025年01月19日22thcjp

给予

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,这样引号就包含在解析结果中的字符串中。
  • 我将 Group 与 key 和 value 一起使用,以便这些值在解析器的输出中配对。
  • ZeroOrMore 允许任意数量的键值对,包括零。

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