本文實(shí)例講述了Python簡單過濾字母和數(shù)字的方法。分享給大家供大家參考,具體如下:
實(shí)例1
crazystring = 'dade142.!0142f[., ]ad'# 只保留數(shù)字new_crazy = filter(str.isdigit, crazystring)print(''.join(list(new_crazy))) #輸出:1420142# 只保留字母new_crazy = filter(str.isalpha, crazystring)print(''.join(list(new_crazy))) #睡出:dadefad# 只保留字母和數(shù)字new_crazy = filter(str.isalnum, crazystring)print(''.join(list(new_crazy))) #輸出:dade1420142fad# 如果想保留數(shù)字0-9和小數(shù)點(diǎn)'.' 則需要自定義函數(shù)new_crazy = filter(lambda ch: ch in '0123456789.', crazystring)print(''.join(list(new_crazy))) #輸出:142.0142.上述代碼運(yùn)行結(jié)果:
1420142
dadefad
dade1420142fad
142.0142.
實(shí)例 2
1.正則表達(dá)式
import reL = ['小明', 'xiaohong', '12', 'adf12', '14']for i in range(len(L)): if re.findall(r'^[^/d]/w+', L[i]): print(re.findall(r'^/w+$', L[i])[0])避開正則表達(dá)式L = ['xiaohong', '12', 'adf12', '14', '曉明']for x in L: try: int(x) except: print(x)
使用string內(nèi)置方法
L = ['xiaohong', '12', 'adf12', '14', '曉明']# 對于python3來說同樣還可以使用string.isnumeric()方法for x in L: if not x.isdigit(): print(x)# for x in L:# if not x.isnumeric():# print(x)
運(yùn)行輸出:
xiaohong
adf12
曉明
實(shí)例 3
要進(jìn)行中文分詞,必須要求數(shù)據(jù)格式全部都是中文,需求過濾掉特殊符號、標(biāo)點(diǎn)、英文、數(shù)字等。當(dāng)然了用戶可以根據(jù)自己的要求過濾自定義字符。
import rex = 'a12121assa'x = '1武林站長站1'r1 = '[a-zA-Z0-9'!"#$%&/'()*+,-./:;<=>?@,。?★、…【】《》?“”‘'![//]^_`{|}~]+'print(re.sub(r1, '', x))運(yùn)行結(jié)果:
武林站長站
參考:https://www.jb51.net/article/154317.htm
PS:這里再為大家提供2款非常方便的正則表達(dá)式工具供大家參考使用:
JavaScript正則表達(dá)式在線測試工具:
http://tools.jb51.net/regex/javascript
正則表達(dá)式在線生成工具:
http://tools.jb51.net/regex/create_reg
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python正則表達(dá)式用法總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選