python - 解析字符串多个分隔符,返回带有样式和文本的元组列表

标签 python markdown pyparsing ply

我正在尝试解析一个字符串,其中包含一些 Markdown 样式分隔符。我需要一份包含样式的列表。我已经尝试使用 pyparsing 并取得了一些成功,但感觉可能有更好的方法(基本上使用 mbeaches 在 http://pyparsing.wikispaces.com/ 的帖子)。

本质上,如果我有一个字符串

word_paragraph = "This is **bold** and this is *italic* sample"

我想在提供后返回元组列表:

style_delim = {'Bold': '**', 'Italics':'*', } 
word_pg_parsed = somefunction(word_paragraph,style_delim)

这会导致 word_pg_parsed 类似于:

word_pg_parsed = [('Normal','This is '),('Bold','bold'),('Normal','and this is '),('Italics','italic'),('Normal',' sample')]

我研究过 markdown,但找不到此功能的存在位置。我怀疑有一个库(深入 PLY 但找不到我想要的东西)可以正确处理这个问题。

为什么?我正在尝试使用 python-docx 文件创建一个 word 文件,其中包括一些标记文本中的一些文本,并且需要相应地处理内联字符样式。 python-markdown 或其他库中是否有任何人见过的东西可以做到这一点?

最佳答案

如果有人想要这样做,这就是我发现的。非常感谢 Waylan 向我指出了库的错误和lepture。

default_output 方法已替换为占位符。这就是您需要重写以获取列表而不是字符串的那个。此处引用:https://github.com/lepture/mistune/pull/20

基本上遵循测试用例中的内容: https://github.com/lepture/mistune/blob/878f92bdb224a8b7830e8c33952bd2f368e5d711/tests/test_subclassing.py getattribute 确实是必需的,否则您会在列表上调用字符串函数时出错。

在 test_subclassing.py 中查找 TokenTreeRenderer。

在我的工作示例的 djangoviews.py 中重复:

from django.shortcuts import render
from .forms import ParseForm   # simple form with textarea field called markup
import mistune


class TokenTreeRenderer(mistune.Renderer):
    # options is required
    options = {}

    def placeholder(self):
        return []

    def __getattribute__(self, name):
        """Saves the arguments to each Markdown handling method."""
        found = TokenTreeRenderer.__dict__.get(name)
        if found is not None:
            return object.__getattribute__(self, name)

        def fake_method(*args, **kwargs):
            return [(name, args, kwargs)]
        return fake_method


def parse(request):
    context = {}
    if request.method == 'POST':
        parse_form = ParseForm(request.POST)
        if parse_form.is_valid():
            # parse the data
            markdown = mistune.Markdown(renderer=TokenTreeRenderer())
            tokenized = markdown(parse_form.cleaned_data['markup'])
            context.update({'tokenized': tokenized, })
            # no need for a redirect in this case

    else:
        parse_form = ParseForm(initial={'markup': 'This is a **bold** text sample', })

    context.update({'form': parse_form, })
    return render(request, 'mctests/parse.html', context)

这会导致输出:

 [('paragraph', ([('text', (u'This is a ',), {}), ('double_emphasis', ([('text', (u'bold',), {})],), {}), ('text', (u' text sample',), {})],), {})]

这对我来说非常有用。

关于python - 解析字符串多个分隔符,返回带有样式和文本的元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34730572/

相关文章:

python - 使用 pyparsing 来匹配字符串的特定结尾

python - PyCharm: "self...."上的自动完成功能不起作用,因为使用了 with_metaclass()

python - 字符串字符同一性悖论

javascript - Python 中的浏览器 'window' 对象等效吗?

markdown - mkdocs 导航标题与页面标题不同

PHP 正则表达式从字符串 Markdown

python - 如何让 PyParsing 识别\x 转义符?

python - Django 模型类和自定义属性

markdown - 如何在 Github-Flavoured-Markdown 中添加元数据?

python - pyparsing 捕获具有给定标题的任意文本组作为嵌套列表