Python簡單過濾字母和數(shù)字的方法小結(jié)
本文實例講述了Python簡單過濾字母和數(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ù)點'.' 則需要自定義函數(shù)
new_crazy = filter(lambda ch: ch in '0123456789.', crazystring)
print(''.join(list(new_crazy))) #輸出:142.0142.
上述代碼運行結(jié)果:
1420142
dadefad
dade1420142fad
142.0142.
實例 2
1.正則表達式
import re
L = ['小明', '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])
避開正則表達式
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)
運行輸出:
xiaohong
adf12
曉明
實例 3
要進行中文分詞,必須要求數(shù)據(jù)格式全部都是中文,需求過濾掉特殊符號、標點、英文、數(shù)字等。當然了用戶可以根據(jù)自己的要求過濾自定義字符。
import re
x = 'a12121assa'
x = '1腳本之家1'
r1 = '[a-zA-Z0-9'!"#$%&\'()*+,-./:;<=>?@,。?★、…【】《》?“”‘'![\\]^_`{|}~]+'
print(re.sub(r1, '', x))
運行結(jié)果:
腳本之家
參考:http://www.dhdzp.com/article/154317.htm
PS:這里再為大家提供2款非常方便的正則表達式工具供大家參考使用:
JavaScript正則表達式在線測試工具:
http://tools.jb51.net/regex/javascript
正則表達式在線生成工具:
http://tools.jb51.net/regex/create_reg
更多關于Python相關內(nèi)容可查看本站專題:《Python正則表達式用法總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Tensorflow: 從checkpoint文件中讀取tensor方式
今天小編就為大家分享一篇Tensorflow: 從checkpoint文件中讀取tensor方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
使用python切片實現(xiàn)二維數(shù)組復制示例
今天小編就為大家分享一篇使用python切片實現(xiàn)二維數(shù)組復制示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11

