在Python中推进slug / url参数化(包括音译)库

时间:2012-01-27 11:00:47

标签: python url slug

我是Python的新手,我正在寻找一个slug / url参数化库,它提供与Ruby Stringex library类似的功能。例如:

# A simple prelude
"simple English".to_url => "simple-english"
"it's nothing at all".to_url => "its-nothing-at-all"
"rock & roll".to_url => "rock-and-roll"

# Let's show off
"$12 worth of Ruby power".to_url => "12-dollars-worth-of-ruby-power"
"10% off if you act now".to_url => "10-percent-off-if-you-act-now"

# You don't even wanna trust Iconv for this next part
"kick it en Français".to_url => "kick-it-en-francais"
"rock it Español style".to_url => "rock-it-espanol-style"
"tell your readers 你好".to_url => "tell-your-readers-ni-hao"

我遇到了webhelpers.text.urlify,它声称这样做 - 结果并不接近。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

检查slugify,该Django's own slugify template filter基于NFKD normalization,但Unidecode。这是相关的代码:

re.sub(r'[-\s]+', '-',
            unicode(
                re.sub(r'[^\w\s-]', '',
                    unicodedata.normalize('NFKD', string)
                    .encode('ascii', 'ignore'))
                .strip()
                .lower()))

它不像Ruby的Stringex那么强大,但你可以轻松扩展它以扩展那些&符号,美元符号等。看看{{3}},Text::Unidecode Perl模块的Python端口, Stringex用于Unicode音译的相同内容。