python - 如何在python中解析重组文本?

标签 python parsing dom restructuredtext

有没有什么模块可以将重组后的文本解析成树模型?

docutils 或 sphinx 可以做到这一点吗?

最佳答案

我想进一步了解 Gareth Latty 的回答。 “您可能想要的是 docutils.parsers.rst 的解析器”是一个很好的答案起点,但下一步是什么?即:

How to parse restructuredtext in python?

以下是 Python 3.6 和 docutils 0.14 的确切答案:

import docutils.nodes
import docutils.parsers.rst
import docutils.utils
import docutils.frontend

def parse_rst(text: str) -> docutils.nodes.document:
    parser = docutils.parsers.rst.Parser()
    components = (docutils.parsers.rst.Parser,)
    settings = docutils.frontend.OptionParser(components=components).get_default_values()
    document = docutils.utils.new_document('<rst-doc>', settings=settings)
    parser.parse(text, document)
    return document

并且可以使用例如下面的方法处理生成的文档,这将打印文档中的所有引用:

class MyVisitor(docutils.nodes.NodeVisitor):

    def visit_reference(self, node: docutils.nodes.reference) -> None:
        """Called for "reference" nodes."""
        print(node)

    def unknown_visit(self, node: docutils.nodes.Node) -> None:
        """Called for all other node types."""
        pass

运行方法如下:

doc = parse_rst('spam spam lovely spam')
visitor = MyVisitor(doc)
doc.walk(visitor)

关于python - 如何在python中解析重组文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12883428/

相关文章:

python - 显示 "bar graph"中列表的内容

python - 从 for 循环中的 if else 语句的最后一行提取信息 Python

python - Python 3 中从外部父类的嵌套类继承的嵌套类

javascript - 在父类上调用方法之前从子元素中删除父类 (javascript/jquery)

python - 在 python 上安装 pandas - numpy 去哪儿了?

java - 将图像插入java代码编辑器

python - [python-3]TypeError : must be str, 不是整数

json - 从 MS Access 在 VBA 中解析 JSON (US BLS)

javascript - 是否可以将 DOM 元素转换为字符串并返回?

javascript - 更改不在 DOM 中的元素的 CSS 属性