将降价标题转换为 Python 中的锚点

Convert markdown title to anchor in Python

我正在尝试将降价标题转换为“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 对 non-alphanumeric 的定义可能与 Markdown 的定义不同。重复破折号和 leading/trailing 破折号的压缩是另一个更精确的领域。

您应该尝试 python-slugify 库来达到您的目的。

以上代码可以替换为

import slugify

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