2016-08-15 53 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' 
相關問題