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



我正在尝试解析一个字符串,该字符串中会有一些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_被解析为类似于:

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

我已经研究了markdown,但找不到这个功能存在的地方。我怀疑有一个图书馆(深入PLY,但找不到我想要的东西)可以正确地处理这件事。

为什么?我正试图使用python-docx文件创建一个单词文件,其中包括一些标记文本中的一些文本,并需要相应地处理内联字符样式。在python markdown或其他库中有人见过这样的东西吗?

如果有人想这样做,下面是我的发现。非常感谢Waylan给我指错了方向,让我去图书馆。

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

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

在testrongubclassing.py.中查找TokenTreeRenderer

在django views.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',), {})],), {})]

这对我来说很好。

最新更新