【问题标题】:Convert markdown title to anchor in Python在 Python 中将 markdown 标题转换为锚点
【发布时间】:2022-01-25 03:00:25
【问题描述】:

我正在尝试将 Markdown 标题转换为“slug”(HTTP 安全)名称 (What is a slug?)。

这是我的尝试:

# this is a heuristic based on what we see in output files - not definitive
def markdown_title_name(t):
    # Strip leading and trailing spaces, use lowercase
    title = t.lower().strip()
    # change non-alphanumeric to dash -, unless we already have a dash
    for i in range(0, len(title)):
        if not title[i].isalnum():
            title = title[0:i] + '-' + title[i+1:]
    # replace any repeated dashes
    while '--' in title:
        title = title.replace('--', '-')
    # remove any leading & trailing dashes
    title = title.strip('-')
    return title

例子:

>>> markdown_title_name('The Quick! Brown Fox\n')
'the-quick-brown-fox'

有没有更好的方法(例如使用可靠的已发布库)来做到这一点?请注意,我不想渲染整个文本,我只想知道名称将解析为什么。

我担心 Python 对非字母数字的定义可能与 Markdown 的定义不同。重复破折号和前导/尾随破折号的压缩是另一个更精确的领域。

【问题讨论】:

    标签: python markdown slug


    【解决方案1】:

    您应该尝试使用python-slugify 库。

    上面的代码可以替换成

    import slugify
    
    def markdown_title_name(t):
        return slugify.slugify(t)
    

    【讨论】:

      猜你喜欢
      • 2017-09-02
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多