Python移除非字母或数字的字符
我在使用Python的正则表达式时遇到了一些小问题。
有没有什么好的方法可以去掉字符串中所有不是字母或数字的字符呢?
谢谢!
7 个回答
9
'\W'
的意思是和 [^A-Za-z0-9_]
一样,除了包含你所在地区的带重音的字符。
>>> re.sub('\W', '', 'text 1, 2, 3...')
'text123'
也许你想保留空格,或者想要所有的单词(和数字):
>>> re.findall('\w+', 'my. text, --without-- (punctuation) 123')
['my', 'text', 'without', 'punctuation', '123']
10
在字符集匹配规则 [...]
中,你可以把 ^
放在第一个位置,表示“不在这个范围内”。
import re
re.sub("[^0-9a-zA-Z]", # Anything except 0..9, a..z and A..Z
"", # replaced with nothing
"this is a test!!") # in this string
--> 'thisisatest'
42
[\w]
匹配字母、数字或下划线。
[\W]
匹配不是字母、数字或下划线的字符,也就是说,它匹配的就是那些不属于字母和数字的东西。
如果你想去掉所有不是字母或数字的字符,就需要用 [\W_]
。
在使用 re.sub() 函数时,如果你能用 [\W_]+
一次性匹配多个字符,而不是一个一个地替换,这样会更高效,因为替换操作是比较耗时的。
现在你只需要定义什么是字母和数字:
str
对象,只包含 ASCII 字母(A-Z、a-z)和数字(0-9):
re.sub(r'[\W_]+', '', s)
str
对象,只包含本地定义的字母和数字:
re.sub(r'[\W_]+', '', s, flags=re.LOCALE)
unicode
对象,包含所有字母和数字:
re.sub(ur'[\W_]+', u'', s, flags=re.UNICODE)
对于 str
对象的示例:
>>> import re, locale
>>> sall = ''.join(chr(i) for i in xrange(256))
>>> len(sall)
256
>>> re.sub('[\W_]+', '', sall)
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
>>> re.sub('[\W_]+', '', sall, flags=re.LOCALE)
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
>>> locale.setlocale(locale.LC_ALL, '')
'English_Australia.1252'
>>> re.sub('[\W_]+', '', sall, flags=re.LOCALE)
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\x83\x8a\x8c\x8e\
x9a\x9c\x9e\x9f\xaa\xb2\xb3\xb5\xb9\xba\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\
xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xde\
xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\
xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff'
# above output wrapped at column 80
Unicode 示例:
>>> re.sub(ur'[\W_]+', u'', u'a_b A_Z \x80\xFF \u0404', flags=re.UNICODE)
u'abAZ\xff\u0404'