2010-09-01 106 views
1

我有這樣蟒蛇:清理字符串

somestring='in this/ string/i have many. interesting.occurrences of {different chars} that need  to .be removed ' 

這裏的字符串是我想要的結果:

somestring='in this string i have many interesting occurrences of different chars that need to be removed' 

我開始手工做各種.replace,但有這麼許多不同的組合,我認爲必須有一個更簡單的方法。也許有一個圖書館已經這樣做?

沒有人知道我該如何清理這個字符串>?

回答

13

我會用正則表達式替換所有的非字母數字爲空格:

>>> import re 
>>> somestring='in this/ string/i have many. interesting.occurrences of {different chars} that need  to .be removed ' 
>>> rx = re.compile('\W+') 
>>> res = rx.sub(' ', somestring).strip() 
>>> res 
'in this string i have many interesting occurrences of different chars that need to be removed' 
+0

wowowow !!這是相當驚人的!我在哪裏可以讀到關於這個圖書館? – 2010-09-01 19:11:35

+3

@user:這只是一個簡單的正則表達式。該庫位於http://docs.python.org/library/re.html。有關正則表達式的更多信息,請參見http://www.regular-expressions.info/。 – kennytm 2010-09-01 19:13:06

+0

http://docs.python.org/library/re.html – leoluk 2010-09-01 19:13:17

1
re.sub('[\[\]/{}.,]+', '', somestring) 
+0

請注意,'interesting.occurrences'需要用空格變成'有趣的事件'。 – kennytm 2010-09-01 19:13:42

+0

多個空間''需要''濃縮爲一個''需要'' – 2010-09-01 20:24:33

+0

是的,你沒事,上面的一個更好。 – leoluk 2010-09-01 20:28:12

2

你有兩個步驟:刪除標點然後刪除多餘的空格。

1)使用string.translate

import string 
trans_table = string.maketrans(string.punctuation, " "*len(string.punctuation) 
new_string = some_string.translate(trans_table) 

這使得然後應用於的標點字符映射到空格轉換表。

2)去除多餘的空白

new_string = " ".join(new_string.split())