Slug 生成器
将任意文本转换为干净的 URL 友好 slug。
URL 别名生成器将标题或短语转换为 URL 友好的别名——一个全小写、用连字符分隔、没有特殊字符或空格的字符串。例如,"我的第一篇博客文章!"变成"my-first-blog-post"。
输入您的标题或短语,工具立即生成干净的别名。转换过程删除重音符号和变音符号、将所有字符转换为小写、用连字符替换空格和标点、删除不是字母数字或连字符的其余字符,并将多个连续连字符合并为一个。
精心设计的 URL 别名通过使 URL 可读且与页面主题相关来提高 SEO。搜索引擎将 URL 中的单词视为相关性信号。保持别名简洁——尽可能省略冠词和介词。对于多语言网站,将非拉丁字符音译,而不是在 URL 中保留为百分号编码序列。
常见问题
代码实现
import re
import unicodedata
def slugify(text: str, separator: str = "-") -> str:
"""Convert text to a URL-friendly slug."""
# Normalize unicode: decompose accented chars (é → e + combining accent)
text = unicodedata.normalize("NFKD", text)
# Encode to ASCII bytes, ignore errors (drops non-ASCII)
text = text.encode("ascii", "ignore").decode("ascii")
# Lowercase
text = text.lower()
# Replace any non-alphanumeric characters with the separator
text = re.sub(r"[^a-z0-9]+", separator, text)
# Strip leading/trailing separators
text = text.strip(separator)
return text
# Examples
print(slugify("Hello, World!")) # hello-world
print(slugify(" Multiple Spaces ")) # multiple-spaces
print(slugify("Héllo Wörld")) # hello-world
print(slugify("C++ is awesome!")) # c-is-awesome
print(slugify("Blog Post #42")) # blog-post-42
print(slugify("Hello World", "_")) # hello_world (underscore)
# For Python web frameworks like Django, use built-in slugify:
# from django.utils.text import slugify
# slugify("Hello, World!") # "hello-world"Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.