2010-09-01 147 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())