Skip to content

Instantly share code, notes, and snippets.

@napoler
Forked from lorey/markdown_to_text.py
Created October 16, 2022 19:56
Show Gist options
  • Save napoler/b6019273b692269d5ebd4c68aff20ed3 to your computer and use it in GitHub Desktop.
Save napoler/b6019273b692269d5ebd4c68aff20ed3 to your computer and use it in GitHub Desktop.
Markdown to Plaintext in Python
from bs4 import BeautifulSoup
from markdown import markdown
def markdown_to_text(markdown_string):
""" Converts a markdown string to plaintext """
# md -> html -> text since BeautifulSoup can extract text cleanly
html = markdown(markdown_string)
# remove code snippets
html = re.sub(r'<pre>(.*?)</pre>', ' ', html)
html = re.sub(r'<code>(.*?)</code >', ' ', html)
# extract text
soup = BeautifulSoup(html, "html.parser")
text = ''.join(soup.findAll(text=True))
return text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment