2016-08-15 176 views
0

我想从Python字符串中除去破折号和空格以外的所有特殊字符。如何从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集合名称,所以希望最终字符串的约束为:允许使用破折号和下划线的字母数字。

回答

1

你实际上是在试图“拼命”你的字符串。

如果你不介意使用第三方(和一个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特异性。


让我们回到你的榜样,你可以把它一个班轮。无论是Python的足够是由你来决定(注意缩短范围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(" ", "_") 


UPDATE似乎有更强大的和Python 3兼容“slugify”库here

0

一行程序,作为请求:

>>> 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' 
相关问题