Python简单过滤字母和数字的方法小结

yipeiwu_com6年前Python基础

本文实例讲述了Python简单过滤字母和数字的方法。分享给大家供大家参考,具体如下:

实例1

crazystring = 'dade142.!0142f[., ]ad'
# 只保留数字
new_crazy = filter(str.isdigit, crazystring)
print(''.join(list(new_crazy))) #输出:1420142
# 只保留字母
new_crazy = filter(str.isalpha, crazystring)
print(''.join(list(new_crazy))) #睡出:dadefad
# 只保留字母和数字
new_crazy = filter(str.isalnum, crazystring)
print(''.join(list(new_crazy))) #输出:dade1420142fad
# 如果想保留数字0-9和小数点'.' 则需要自定义函数
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

要进行中文分词,必须要求数据格式全部都是中文,需求过滤掉特殊符号、标点、英文、数字等。当然了用户可以根据自己的要求过滤自定义字符。

import re
x = 'a12121assa'
x = '1【听图阁-专注于Python设计】1'
r1 = '[a-zA-Z0-9'!"#$%&\'()*+,-./:;<=>?@,。?★、…【】《》?“”‘'![\\]^_`{|}~]+'
print(re.sub(r1, '', x))

运行结果:

【听图阁-专注于Python设计】

参考/post/154317.htm

PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:

JavaScript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript

正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg

更多关于Python相关内容可查看本站专题:《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python使用matplotlib实现在坐标系中画一个矩形的方法

Python使用matplotlib实现在坐标系中画一个矩形的方法

本文实例讲述了Python使用matplotlib实现在坐标系中画一个矩形的方法。分享给大家供大家参考。具体实现方法如下: import matplotlib.pyplot as p...

Python深入学习之闭包

闭包(closure)是函数式编程的重要的语法结构。函数式编程是一种编程范式 (而面向过程编程和面向对象编程也都是编程范式)。在面向过程编程中,我们见到过函数(function);在面向...

python实现ID3决策树算法

ID3决策树是以信息增益作为决策标准的一种贪心决策树算法 # -*- coding: utf-8 -*- from numpy import * import math imp...

Python提取转移文件夹内所有.jpg文件并查看每一帧的方法

python里面可以将路径里面的\替换成/避免转义。 os.walk方法可以将目标路径下文件的root,dirs,files提取出来。后面对每个文件进行操作。 切片操作[:]判断是否为....

pandas 空的dataframe 插入列名的示例

如下所示: colum = ['性别','年龄','M','样本类型'] + muta_list + ['B'] data1 = pd.DataFrame(columns=colum...