Python中使用正则表达式
来源:互联网 发布:炒股日记软件 编辑:程序博客网 时间:2024/05/19 04:53
Python中使用正则表达式
标签: Python编程正则表达式字符串
2013-07-30 19:49 23776人阅读 评论(1)收藏举报
本文章已收录于:
分类:
作者同类文章X
版权声明:本文为博主原创文章,未经博主允许不得转载。
本文通过示例来描述如何在Python中使用正则表达式来统计文本中的所有数字。
示例中的文本来自命令行的管道数据,
- sys.stdin.readlines()
主要是因为作者需要在命令行的输出信息中做数字统计。
示例代码1,列出根目录下所有文件或文件夹的名称字符串中包含的数字
- import re
- for name in sys.stdin.readlines():
- items = re.findall("\d+", name)
- if(len(items)>0):
- print items
执行命令:
$ ls /
bin boot cdrom dev etc home initrd.img initrd.img.old lib lib32 lib64 libx32 lost+found media mnt opt proc root run sbin selinux srv sys tmp usr var vmlinuz vmlinuz.old
$ ls / | python test.py
输出结果:
['32']
['64']
['32']
示例代码2:找出管道输出文本中的所有数字,并求和
- import sys;
- import re
- items = []
- for name in sys.stdin.readlines():
- nums = re.findall("\d+", name)
- for num in nums:
- items.append(num)
- if(len(items)>0):
- print items
- sumNum = 0
- for num in items:
- sumNum += int(num)
- print "Total:",sumNum
正则表达式的规则如下图:
- 顶
- 4
- 踩
- 1
- 上一篇Python脚本中使用命令行管道数据
- 下一篇用Python正则表达式搜索统计命令行管道中的所有数字
0 0
- Python中使用正则表达式
- Python中使用正则表达式
- python中使用 正则表达式
- Python中使用正则表达式
- Python中使用正则表达式
- Python中使用正则表达式
- 在python 中使用正则表达式
- Python中正则表达式的使用
- 【转载】Python中使用正则表达式 详解
- Python 中正则表达式的使用浅析
- Python中正则表达式的使用
- Python中正则表达式的使用
- python中正则表达式
- python中正则表达式
- Python中正则表达式
- python中正则表达式
- python正则表达式使用
- python使用正则表达式
- [Gradle]Error:java.lang.OutOfMemoryError: Java heap space . Please assign more memory to Gradle in t
- 反对项目经理在项目计划中把程序员标志为“资源”
- Saving Key-Value Sets 官方文档翻译
- LingPipe深度剖析
- 银行卡验证
- Python中使用正则表达式
- Content type 'text/plain;charset=UTF-8' not supported
- Ubuntu下配置JDK环境变量
- C# Directory类的操作
- opencv3.1(python3.5)安装
- postcore_initcall(), arch_initcall(), subsys_initcall(), device_initcall() 调用顺序
- LeetCode - Best Time to Buy and Sell Stock III
- android为listview计算出实际需要的高度
- 自定义的对话框