Python : How to convert markdown formatted text to text Python : How to convert markdown formatted text to text python python

Python : How to convert markdown formatted text to text


The Markdown and BeautifulSoup (now called beautifulsoup4) modules will help do what you describe.

Once you have converted the markdown to HTML, you can use a HTML parser to strip out the plain text.

Your code might look something like this:

from bs4 import BeautifulSoupfrom markdown import markdownhtml = markdown(some_html_string)text = ''.join(BeautifulSoup(html).findAll(text=True))


Despite the fact that this is a very old question, I'd like to suggest a solution I came up with recently. This one neither uses BeautifulSoup nor has an overhead of converting to html and back.

The markdown module core class Markdown has a property output_formats which is not configurable but otherwise patchable like almost anything in python is. This property is a dict mapping output format name to a rendering function. By default it has two output formats, 'html' and 'xhtml' correspondingly. With a little help it may have a plaintext rendering function which is easy to write:

from markdown import Markdownfrom io import StringIOdef unmark_element(element, stream=None):    if stream is None:        stream = StringIO()    if element.text:        stream.write(element.text)    for sub in element:        unmark_element(sub, stream)    if element.tail:        stream.write(element.tail)    return stream.getvalue()# patching MarkdownMarkdown.output_formats["plain"] = unmark_element__md = Markdown(output_format="plain")__md.stripTopLevelTags = Falsedef unmark(text):    return __md.convert(text)

unmark function takes markdown text as an input and returns all the markdown characters stripped out.


Commented and removed it because I finally think I see the rub here: It may be easier to convert your markdown text to HTML and remove HTML from the text. I'm not aware of anything to remove markdown from text effectively but there are many HTML to plain text solutions.