【问题标题】:pyparsing results as a JSON将结果解析为 JSON
【发布时间】:2013-05-22 04:29:32
【问题描述】:

在网上浏览了一天后,我在这里问这个问题:

有什么方法可以得到 pyparsing 结果,f.e.

result = longSentence.parseString(text.lower())

采用 JSON 格式?

2013 年 5 月 27 日 11:46 更新:
好的。所以我尝试制作一个简单的英语解析器。
句子“走 5 米,你看到了什么?”的结果现在打印为列表:

[[[['go'], [['5', 'metres']]]], 'and', ['what do you see?']]

['what do you see?'] 标记为SetResultsName('Question')
其他标记为类似。

如果它能够以这种形式打印该数据,那就太好了:

{
    "Sentence1":
    {
        "Order":
        {
            "Predicate": 'go',
            "Subject": ['5', 'metres']
        }
    },
    "Sentence2":
    {
        "Question": 'what do you see?'
    }
}

【问题讨论】:

    标签: python json python-2.7 pyparsing


    【解决方案1】:

    好的。在再次尝试查看文档后,我发现了一种以 XML 形式返回此数据的非常好的方法:

    result = longSentence.parseString(text.lower()).asXML()
    

    如果我添加this question with answers - 就完成了。所以要得到 JSON 形式的结果不是那么容易,也不是那么难。我希望有需要的人能找到。

    【讨论】:

      【解决方案2】:

      您必须更加明确,但一般方法是获取解析结果并使用 json 模块(无论您希望它作为嵌套字典/列表、扁平列表/等...由你决定)

      import json
      json_string = json.dumps(result.asList())
      

      【讨论】:

      • 这会将所有内容表示为列表并删除所有.setResultName
      猜你喜欢
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-30
      • 2014-03-23
      相关资源
      最近更新 更多