from nltk.corpus.reader.markdown import MarkdownCorpusReader
from nltk.tokenize.treebank import TreebankWordDetokenizer
# You might also need a punkt detokenizer for the English language.
filepath = './some/path/here'
reader = MarkdownCorpusReader(filepath, r'[w\]*\.md')
def get_text(reader: MarkdownCorpusReader, fileid: str) -> str:
tokens = reader.words(fileids=fileid)
# You might also need a punkt detokenizer for the English language.
return TreebankWordDetokenizer().detokenize(tokens)
6条答案
按热度按时间ozxc1zmp1#
尽管这是一个非常古老的问题,但我还是想提出一个我最近想出的解决方案。这一个既不使用BeautifulSoup,也没有转换为html和回来的开销。
markdown模块核心类Markdown有一个属性output_formats,它是不可配置的,但可以像python中的几乎任何东西一样打补丁。此属性是将输出格式名称Map到呈现函数的dict。默认情况下,它有两种输出格式,相应地'html'和'xhtml'。只要有一点帮助,它就可以有一个很容易编写的明文渲染函数:
unmark函数接受markdown文本作为输入,并返回所有删除的markdown字符。
4nkexdtk2#
Markdown和BeautifulSoup(现在称为 beautifulsoup4)模块将帮助完成您所描述的任务。
将markdown转换为HTML后,可以使用HTML解析器去除纯文本。
你的代码可能看起来像这样:
gtlvzcf83#
这与Jason的答案类似,但正确处理了注解。
7nbnzgx94#
评论并删除它,因为我终于认为我看到了这里的摩擦:将markdown文本转换为HTML并从文本中删除HTML可能更容易。我不知道有什么可以有效地从文本中删除markdown,但有许多HTML到纯文本的解决方案。
ymzxtsji5#
在我有限的经验中,这不一定是一个非常快的解决方案,但您可以尝试NLTK的MarkdownCorpusReader。它需要一个满是markdown文件的目录和一个有效文件ID的正则表达式。
不幸的是,markdown上有一些变量,所以根据它来自哪里,一些格式元素可能仍然存在。我不能完全测试这一点,因为我没有示例数据。你可能还需要一个英语的punkt detokenizer。我对这里使用的默认标记化不是很熟悉,但我认为它是nltk。tokenize.word_tokenize,它使用树库分词器+英语标点分词器的组合。
我还要补充一点,nlkt的markdown阅读器是基于markdown-it-py和mdit-plain构建的,所以这些模块中可能也有工具可以帮助实现这一点。
velaa5lx6#
我来这里是为了寻找一种表演的方法。c. GitLab Releases通过API call。我希望这与原始提问者的用例相匹配。
我将markdown解码为纯文本(包括
\n
等形式的空格)。)以那种方式: