【发布时间】: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 的定义不同。重复破折号和前导/尾随破折号的压缩是另一个更精确的领域。
【问题讨论】: