亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python簡單過濾字母和數(shù)字的方法小結

 更新時間:2019年01月09日 11:25:05   作者:致Great  
這篇文章主要介紹了Python簡單過濾字母和數(shù)字的方法,涉及Python基于內置函數(shù)與正則表達式進行字母和數(shù)字過濾的相關操作技巧,需要的朋友可以參考下

本文實例講述了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.

上述代碼運行結果:

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內置方法

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))

運行結果:

腳本之家

參考http://chabaoo.cn/article/154317.htm

PS:這里再為大家提供2款非常方便的正則表達式工具供大家參考使用:

JavaScript正則表達式在線測試工具:
http://tools.jb51.net/regex/javascript

正則表達式在線生成工具:
http://tools.jb51.net/regex/create_reg

更多關于Python相關內容可查看本站專題:《Python正則表達式用法總結》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對大家Python程序設計有所幫助。

相關文章

最新評論