2015-06-07 31 views
4

我試圖從字符串中除去空格以外的所有非字母數字字符,但似乎無法弄清楚我如何排除空間。目前,我正在做這種方式:Python:嘗試降低字符串並從空格中刪除非字母數字字符

re.sub('[\W_]+', '', text).lower().strip() 

但運行我的功能產生以下結果:

print removePunctuation('Hi, you!') 
print removePunctuation(' No under_score!') 
hiyou 
nounderscore 

,我想它是:

hi you 
no underscore 

所以,我該怎麼辦排除空間被替換?

我的現行最佳是這樣的:

re.sub('[^\s\w]+', '', text).lower().strip().replace('_','') 
+0

您是否也想刪除開頭和結尾的空格? – pzp

回答

6

你可以使用這個,

re.sub(r'[^\sa-zA-Z0-9]', '', text).lower().strip() 

例子:

>>> import re 
>>> def removePunctuation(s): 
     return re.sub(r'[^\sa-zA-Z0-9]', '', s).lower().strip() 

>>> print removePunctuation('Hi, you!') 
hi you 
>>> print removePunctuation(' No under_score!') 
no underscore 

OR

re.sub('(?!\s)[\W_]', '', text).lower().strip() 
+0

除了下劃線仍然存在 –

+0

現在,它會很好.. –

+0

謝謝!將接受它,除非出現更接近我的解決方案的東西。 –

-1

您可以從阿瑟賽德解決這個問題:

re.sub('([^\w ]|_)+', '', 'a ,_ b').lower().strip() 

它給a b

所以你說:刪除所有不是字母數字字符,而不是一個空間或者是下劃線字符。

+0

除'_'將仍然包括 –

+0

'_'也需要刪除 –

+0

現在應該可以 – LisuBB

0

你可能會喜歡列表理解更好地在這裏:

result = ''.join([c for c in myString if str.isalnum(c) or str.isspace(c)]) 
+0

使用'''.join(c for c in myString if str.isalnum (c)或str.isspace(c))將節省內存。 –

+0

@EliKorvigo,不,如果你通過一個生成器表達式加入 –

+0

@PadraicCunningham,它不會首先建立一個列表,這是一件很棒的事情,謝謝。順便說一句,你是怎麼發現的?我查找了「join」方法源,並且它們什麼也沒有顯示。 –

0

怎麼樣產生的理解?它比使用RegExp更可讀。

def removePunctuation(s): 
    return ''.join(l for l in s if l.isalnum() or l == ' ').lower().strip() 

或者作爲lambda

removePunctuation = lambda s: ''.join(l for l in s if l.isalnum() or l == ' ').lower().strip() 
0

您可以刪除標點與str.translate:

s = 'Hi, you!' 

from string import punctuation 

print(s.translate(None,punctuation).lower()) 
hi you 

對於python3:

s = 'Hi, you!' 

from string import punctuation 

print(s.translate({ord(k):"" for k in punctuation}).lower()) 
hi you 

在功能:

from string import punctuation 

def remove_punctuation(s): 
    return s.translate(None,punctuation).lower() 

def remove_punctuation(s): 
    return s.translate({ord(k): "" for k in punctuation}).lower() 

輸出:

In [3]: remove_punctuation(' No under_score!') 
Out[3]: ' no underscore' 

In [4]: remove_punctuation('Hi, you!') 
Out[4]: 'hi you' 

如果你想刪除前導空格添加帶。

from string import punctuation 
def remove_punctuation(s): 
    return s.translate(None,punctuation).lower().strip() 

輸出:

In [6]: remove_punctuation(' No under_score!') 
Out[6]: 'no underscore' 

In [7]: remove_punctuation('Hi, you!') 
Out[7]: 'hi you' 
相關問題