-
-
Save chrissimpkins/67d1f18b01bfba7978e8fb04268ab92d to your computer and use it in GitHub Desktop.
Extract the plain text from markdown, for plain text search.
This file contains hidden or 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
import commonmark | |
with open('test.md', 'r') as myfile: | |
text = myfile.read() | |
parser = commonmark.Parser() | |
ast = parser.parse(text) | |
# Returns the text from markdown, stripped of the markdown syntax itself | |
def ast2text(astNode): | |
walker = astNode.walker() | |
acc = ""; | |
iterator = iter(walker) | |
while True: | |
try: | |
(current, entering) = next(iterator) | |
except StopIteration: | |
break # Iterator exhausted: stop the loop | |
else: | |
print("- - - - - - -") | |
print(f"{entering} \"{current.t}\": \"{current.literal}\"") | |
# Add the text | |
if current.literal: | |
acc += current.literal | |
# Add in the missing line breaks | |
if current.t == "linebreak": | |
acc += "\n" | |
if current.t == "paragraph" and entering == False: | |
acc += "\n\n" | |
if current.t == "heading" and entering == False: | |
acc += "\n" | |
print("") | |
return acc.strip() | |
print(ast2text(ast)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment