Django: autoslug -> 自定义 slugifier
我遇到一个问题。我想创建一个自定义的slugify函数。我使用的是 django.autoslug。根据autoslug的文档,我能够创建一个自定义的slugifier,但我觉得它还需要改进,而我不知道该怎么做。
我有一个字符串(书名),比如 .NET Framework 4.0 with C# & VB in VisualStudio 2010
。我想把它转换成slug格式,变成这样: 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),但我不知道该怎么做,也不知道如何用正确的方式替换匹配到的字符串。
有什么想法吗?!
附言:抱歉我的英语不好
1 个回答
0
import re
point = re.compile( r"(?<=\d)\.(?=\d)" )
point.sub( value, "point" )
要把那些应该是 "point"
的 .
改掉,然后用 str.replace
来替换其他的。
解释
point
是用来匹配夹在两个数字之间的 .
。
(?<=spam)ham(?=eggs)
是一种(正向)前后查找。它的意思是“匹配 ham
,前面必须是 spam
,后面必须是 eggs
”。换句话说,它告诉正则表达式引擎在匹配的模式周围“看看”。