Last active
July 18, 2024 05:53
-
-
Save lorey/eb15a7f3338f959a78cc3661fbc255fe to your computer and use it in GitHub Desktop.
Markdown to Plaintext in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from bs4 import BeautifulSoup | |
from markdown import markdown | |
import re | |
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