Django:autoslug ->定制粉碎机
我有一个问题。我正在尝试创建一个自定义的 slugify 函数。我使用 django.autoslug。由于 autoslug 文档,我能够创建一个自定义 slugifier,但它需要改进,我不知道如何实现这一点。
所以我有一个字符串(书名),即 .NET Framework 4.0 with C# & VisualStudio 2010 中的 VB
。我想将其简化为如下所示: dotnet-framework-4point0-with-cshapr-and-vb-in-visualstudio-2010
我当前的函数如下所示:
def custom_slug(value, *args, **kwargs):
associations_dict = {'#':'sharp', '.':'dot', '&':'and'}
for searcg_char in associations_dict.keys():
if search_char in value:
value = value.replace(search_char, associations_dict[search_char])
return def_slugify(value)
如您所见,我的函数将所有点 .
替换为 'dot'
。所以我的字符串将更改为 dotnet-framework-4dot0-with-csharp-and-vb-in-visualstudio-2010
我建议,我应该使用 RegEx,但我不知道该怎么做这以及如何用正确的“点/点替换”想法替换匹配的字符串
?
PS抱歉英语不好
I have a prob. I'm trying to create a custom slugify functiom. I use django.autoslug. Due to autoslug documentation I was able to create a custom slugifier, but it needs to be improved and I do not know how do I realize that.
So I have a string (book title) i.e. .NET Framework 4.0 with C# & VB in VisualStudio 2010
. I want to slugify it so that it looks like this: dotnet-framework-4point0-with-cshapr-and-vb-in-visualstudio-2010
My current function looks like this:
def custom_slug(value, *args, **kwargs):
associations_dict = {'#':'sharp', '.':'dot', '&':'and'}
for searcg_char in associations_dict.keys():
if search_char in value:
value = value.replace(search_char, associations_dict[search_char])
return def_slugify(value)
As you can see, my function replaces all dots .
with 'dot'
. So my string will be changed into dotnet-framework-4dot0-with-csharp-and-vb-in-visualstudio-2010
I suggest, I should use RegEx, but I don't know how to do this and how do I replace matched string with right 'dot/point-replacement'
Ideas ?!
P.S. Sorry for bad English
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
更改应为
"point"
的.
,然后执行str.replace
更改其他内容。解释
point
匹配夹在两个数字之间的.
。(?<=spam)ham(?=eggs)
是一个(正)环顾四周。它的意思是“匹配ham
,只要它前面是spam
,后面是eggs
”。换句话说,它告诉正则表达式引擎“环视”它匹配的模式。to change the
.
s that should be"point"
, and then dostr.replace
to change the others.Explanation
point
matches a.
which is sandwiched between two digits.(?<=spam)ham(?=eggs)
is a (positive) lookaround. It means "matchham
, as long as it is preceded byspam
and followed byeggs
". In other words, it tells the regex engine to "look around" the pattern that it is matching.