[英]Converting result set to a dict with pyparsing
I'm trying to convert the result set of parsing to a dict with pyparsing.我正在尝试使用 pyparsing 将解析结果集转换为字典。 But dictionary contains only the last member of result set, not all of them.
但是字典只包含结果集的最后一个成员,而不是全部。 What am i missing?
我错过了什么?
Here's my code:这是我的代码:
from pyparsing import *
test = """
pci24 u2480-L0
fcs1 g4045-L1
pci25 h6045-L0
en192 v7024-L3
pci26 h6045-L1
"""
grammar_pci = Combine("pci" + Word( nums )).setResultsName("name") + Word( alphanums + "-" ).setResultsName("loc")
grammar_non_pci = Suppress( Regex( r"(?!pci).*" ) )
grammar = OneOrMore( Group(grammar_pci).setResultsName("pci_slots") | grammar_non_pci, stopOn=StringEnd())
def main():
data = grammar.parse_string(test, parseAll=True)
print(data)
data_dict = data.as_dict()
print(data_dict)
if __name__ == "__main__":
main()
And the outputs of data and data_dict:以及 data 和 data_dict 的输出:
[['pci24', 'u2480-L0'], ['pci25', 'h6045-L0'], ['pci26', 'h6045-L1']]
{'pci_slots': {'name': 'pci26', 'loc': 'h6045-L1'}}
pyparsing version: 3.0.9 pyparsing版本:3.0.9
I hope, this will fix the issue (set listAllMatches=True in setResultName of 'pci_slots')我希望,这将解决问题(在“pci_slots”的 setResultName 中设置 listAllMatches=True)
from pyparsing import *
test = """
pci24 u2480-L0
fcs1 g4045-L1
pci25 h6045-L0
en192 v7024-L3
pci26 h6045-L1
"""
grammar_pci = Combine("pci" + Word( nums )).setResultsName("name") + Word( alphanums + "-" ).setResultsName("loc")
grammar_non_pci = Suppress( Regex( r"(?!pci).*" ) )
grammar = OneOrMore( Group(grammar_pci).setResultsName("pci_slots", listAllMatches=True) | grammar_non_pci, stopOn=StringEnd())
data = grammar.parse_string(test, parseAll=True)
print(data)
data_dict = data.as_dict()
print(data_dict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.