【发布时间】:2020-01-14 00:46:07
【问题描述】:
我想转换自:
输入:
"#serviceRequest and @charges:getRoamingCharges or @plans:dataplans"
'#' - 意图 '@' - 实体 ':'-值
输出:
{"and":[
{"some" : [ {"var":"intents"}, {"==":[{"var":"intent"}]},
"serviceRequest"]},
{"or":[
{"and":[{"some" : [ {"var":"entities"}, {"==":[{"var":"entity"},
"charges"]} ]},
{"some" : [ {"var":"entities"}, {"==":[{"var":"value"},
"getRoamingCharges"]} ]}]
},{"and":[
{"some" : [ {"var":"entities"}, {"==":[{"var":"entity"}, "plans"]}
]},
{"some" : [ {"var":"entities"}, {"==":[{"var":"value"}, "data
plans"]} ]}
]}
]}
]}
我尝试过的:
import pyparsing
identifier = pyparsing.QuotedString('"')
operator = (
pyparsing.Literal("==") |
pyparsing.Literal("≠") |
pyparsing.Literal("≥") |
pyparsing.Literal("≤") |
pyparsing.Literal("<") |
pyparsing.Literal(">")
)
value = pyparsing.QuotedString('"')
match_format = identifier + operator + value
#print(match_format.parseString('"foobar"=="123"'))
def list_to_dict(pos, tokens):
dic = {}
lis =[]
print(tokens)
abc= {tokens[1]: {tokens[2], tokens[0]}}
print(abc)
lis.append(abc)
dic['bfeh']=lis
return tokens
match_format = (identifier + operator +
value).setParseAction(list_to_dict)
print(match_format.parseString('"intent"=="serviceRequest"'))
给:
{'==': {'intent', 'serviceRequest'}}
请帮助我使用 Parsing (Python) 或任何您想要的替代方法?
【问题讨论】:
-
到目前为止你有什么尝试?
-
@MaximeGirou 请检查更新的问题
-
您在示例代码中解析的字符串与带有“#”、“@”标记的输入字符串几乎没有相似之处。
标签: python json parsing pyparsing