我这里有代码:
#parser.py
import pyparsing as pp
class parser:
def __init__(self):
self.integer = pp.Word(pp.nums).set_results_name('int')
self.string1 = pp.QuotedString(quoteChar='"')
self.string2 = pp.QuotedString(quoteChar="'")
self.string = pp.Or([self.string1, self.string2]).set_results_name('str')
self.object = pp.Or([self.string, self.integer])
self.tuple = '(' + pp.delimited_list(self.object, delim=',') + ')'
self.tuple = self.tuple.set_results_name('tuple')
self.object = pp.Or([self.string, self.integer, self.tuple])
self.varname = pp.Word(pp.alphas + "_").set_results_name('varname')
self.let_ = pp.Keyword('let')
self.const_ = pp.Keyword('const')
self.var_ = pp.Keyword('var')
self.set_ = pp.one_of(": =")
self.variable = pp.Or([pp.Or([self.let_, self.const_, self.var_]) + self.varname + self.set_ + self.object,
self.varname + self.set_ + self.object])
def parseVar(self, string):
return self.variable.parse_string(string)
#main.py
from parser import parser
parse = parser()
print(parse.parseVar('hi = ("hi", 2)').as_dict())
然后我得到:
{"varname":"hi', 'str': 'hi',int:"2', "tuple': ['(", 'hi', '2', ')']}
抱歉“和’交换了 - [编辑]已为您修正)但我想得到的是:
{"varname": "hi", "tuple": {"str":"hi", "int":"2"}}
有没有任何方式可以获得这个结果?