Django:autoslug ->定制粉碎机

发布于 2024-09-12 17:24:09 字数 970 浏览 5 评论 0原文

我有一个问题。我正在尝试创建一个自定义的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

别挽留 2024-09-19 17:24:09
import re
point = re.compile( r"(?<=\d)\.(?=\d)" )
point.sub( value, "point" )

更改应为 "point". ,然后执行 str.replace 更改其他内容。

解释

point 匹配夹在两个数字之间的 .

(?<=spam)ham(?=eggs) 是一个(正)环顾四周。它的意思是“匹配ham,只要它前面是spam,后面是eggs”。换句话说,它告诉正则表达式引擎“环视”它匹配的模式。

import re
point = re.compile( r"(?<=\d)\.(?=\d)" )
point.sub( value, "point" )

to change the . s that should be "point" , and then do str.replace to change the others.

Explanation

point matches a . which is sandwiched between two digits.

(?<=spam)ham(?=eggs) is a (positive) lookaround. It means "match ham, as long as it is preceded by spam and followed by eggs". In other words, it tells the regex engine to "look around" the pattern that it is matching.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文