如何从Python字符串中删除除空格和短划线之外的所有特殊字符?

时间:2016-08-15 07:05:24

标签: regex python-2.7

我想从Python字符串中删除所有特殊字符,但破折号和空格除外。

这是对的吗?

import re
my_string = "Web's GReat thing-ok"
pattern = re.compile('[^A-Za-z0-9 -]')
new_string = pattern.sub('',my_string)
new_string
>> 'Webs GReat thing-ok'
# then make it lowercase and replace spaces with underscores
# new_string = new_string.lower().replace (" ", "_")
# new_string
# >> 'webs_great_thing-ok'

如图所示,我最终想要在删除其他特殊字符后用下划线替换空格,但我想我会分阶段进行。是否有一种Pythonic方式一举完成这一切?

对于上下文,我将此输入用于MongoDB集合名称,因此希望最终字符串的约束为:允许使用破折号和下划线的字母数字。

2 个答案:

答案 0 :(得分:2)

你实际上是在试图" slugify"你的字符串。

如果您不介意使用第三方(以及特定于Python 2)的库,则可以使用slugifypip install slugify):

import slugify

string = "Web's GReat thing-ok"
print slugify.slugify(string)
>> 'webs_great_thing-ok'

您可以自己实施。 slugify的所有代码都是

import re
import unicodedata

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

请注意,这是Python 2特有的。


回到你的例子,你可以把它变成一个单行。是否Pythonic足以由您决定(注意缩短的范围A-z而不是A-Za-z):

import re

my_string = "Web's GReat thing-ok"
new_string = re.sub('[^A-z0-9 -]', '', my_string).lower().replace(" ", "_")


更新似乎更强大,Python 3兼容" slugify"图书馆here

答案 1 :(得分:1)

根据要求提出单行程序:

>>> import re, unicodedata
>>> value = "Web's GReat thing-ok"
>>> re.sub('[\s]+', '_', re.sub('[^\w\s-]', '', unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore').decode('ascii')).strip().lower())
u'webs_great_thing-ok'