Python:如何将Markdown格式的文本转换为文本

xiozqbni  于 2023-04-28  发布在  Python
关注(0)|答案(6)|浏览(238)

我需要转换为纯文本格式的markdown文本显示摘要在我的网站。我想要Python的代码。

ozxc1zmp

ozxc1zmp1#

尽管这是一个非常古老的问题,但我还是想提出一个我最近想出的解决方案。这一个既不使用BeautifulSoup,也没有转换为html和回来的开销。

markdown模块核心类Markdown有一个属性output_formats,它是不可配置的,但可以像python中的几乎任何东西一样打补丁。此属性是将输出格式名称Map到呈现函数的dict。默认情况下,它有两种输出格式,相应地'html'和'xhtml'。只要有一点帮助,它就可以有一个很容易编写的明文渲染函数:

from markdown import Markdown
from io import StringIO

def 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 Markdown
Markdown.output_formats["plain"] = unmark_element
__md = Markdown(output_format="plain")
__md.stripTopLevelTags = False

def unmark(text):
    return __md.convert(text)

unmark函数接受markdown文本作为输入,并返回所有删除的markdown字符。

4nkexdtk

4nkexdtk2#

MarkdownBeautifulSoup(现在称为 beautifulsoup4)模块将帮助完成您所描述的任务。
将markdown转换为HTML后,可以使用HTML解析器去除纯文本。
你的代码可能看起来像这样:

from bs4 import BeautifulSoup
from markdown import markdown

html = markdown(some_html_string)
text = ''.join(BeautifulSoup(html).findAll(text=True))
gtlvzcf8

gtlvzcf83#

这与Jason的答案类似,但正确处理了注解。

import markdown # pip install markdown
from bs4 import BeautifulSoup # pip install beautifulsoup4

def md_to_text(md):
    html = markdown.markdown(md)
    soup = BeautifulSoup(html, features='html.parser')
    return soup.get_text()

def example():
    md = '**A** [B](http://example.com) <!-- C -->'
    text = md_to_text(md)
    print(text)
    # Output: A B
7nbnzgx9

7nbnzgx94#

评论并删除它,因为我终于认为我看到了这里的摩擦:将markdown文本转换为HTML并从文本中删除HTML可能更容易。我不知道有什么可以有效地从文本中删除markdown,但有许多HTML到纯文本的解决方案。

ymzxtsji

ymzxtsji5#

在我有限的经验中,这不一定是一个非常快的解决方案,但您可以尝试NLTK的MarkdownCorpusReader。它需要一个满是markdown文件的目录和一个有效文件ID的正则表达式。

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)

不幸的是,markdown上有一些变量,所以根据它来自哪里,一些格式元素可能仍然存在。我不能完全测试这一点,因为我没有示例数据。你可能还需要一个英语的punkt detokenizer。我对这里使用的默认标记化不是很熟悉,但我认为它是nltk。tokenize.word_tokenize,它使用树库分词器+英语标点分词器的组合。
我还要补充一点,nlkt的markdown阅读器是基于markdown-it-py和mdit-plain构建的,所以这些模块中可能也有工具可以帮助实现这一点。

velaa5lx

velaa5lx6#

我来这里是为了寻找一种表演的方法。c. GitLab Releases通过API call。我希望这与原始提问者的用例相匹配。
我将markdown解码为纯文本(包括\n等形式的空格)。)以那种方式:

with open("release_note.md", 'r') as file:
        release_note = file.read()
        description = bytes(release_note, 'utf-8')
    return description.decode("utf-8")

相关问题