Python中的字符串slugification [英] String slugification in Python

查看:78
本文介绍了Python中的字符串slugification的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找slugify"字符串的最佳方法什么是slug"是,我目前的解决方案是基于 这个食谱

I am in search of the best way to "slugify" string what "slug" is, and my current solution is based on this recipe

我已将其更改为:

s = 'String to slugify'

slug = unicodedata.normalize('NFKD', s)
slug = slug.encode('ascii', 'ignore').lower()
slug = re.sub(r'[^a-z0-9]+', '-', slug).strip('-')
slug = re.sub(r'[-]+', '-', slug)

有人看到这段代码有什么问题吗?它工作正常,但也许我遗漏了什么或者你知道更好的方法?

Anyone see any problems with this code? It is working fine, but maybe I am missing something or you know a better way?

推荐答案

有一个名为 python-slugify,它在 slugify 方面做得很好:

There is a python package named python-slugify, which does a pretty good job of slugifying:

pip install python-slugify

工作方式如下:

from slugify import slugify

txt = "This is a test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")

txt = "This -- is a ## test ---"
r = slugify(txt)
self.assertEquals(r, "this-is-a-test")

txt = 'C\'est déjà l\'été.'
r = slugify(txt)
self.assertEquals(r, "cest-deja-lete")

txt = 'Nín hǎo. Wǒ shì zhōng guó rén'
r = slugify(txt)
self.assertEquals(r, "nin-hao-wo-shi-zhong-guo-ren")

txt = 'Компьютер'
r = slugify(txt)
self.assertEquals(r, "kompiuter")

txt = 'jaja---lol-méméméoo--a'
r = slugify(txt)
self.assertEquals(r, "jaja-lol-mememeoo-a")

参见更多示例

这个包比你发布的要多一些(看看源,它只是一个文件).该项目仍然处于活动状态(在我最初回答前 2 天更新,七年后(最后一次检查 2020-06-30),它仍然得到更新).

This package does a bit more than what you posted (take a look at the source, it's just one file). The project is still active (got updated 2 days before I originally answered, over seven years later (last checked 2020-06-30), it still gets updated).

小心:还有第二个包,名为slugify.如果您同时拥有它们,您可能会遇到问题,因为它们具有相同的导入名称.刚刚命名的 slugify 并没有完成我快速检查的所有内容:"Ich heiße" 变成了 "ich-heie"(应该是 "ich-heisse"),所以在使用 pipeasy_install 时一定要选择正确的.

careful: There is a second package around, named slugify. If you have both of them, you might get a problem, as they have the same name for import. The one just named slugify didn't do all I quick-checked: "Ich heiße" became "ich-heie" (should be "ich-heisse"), so be sure to pick the right one, when using pip or easy_install.

这篇关于Python中的字符串slugification的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆