python正则表达式练习篇
2016-02-23 19:56
671 查看
练习一:
利用who命令输出所有已经登录系统的用户的信息,并把登录名、用户登录时的电传、登录时间、登录地址利用正则表达式分割开来。数据的格式:
%who wesc console Jun 20 20:33 wesc pts/9 Jun 22 01:38 (192.168.0.6) wesc pts/1 Jun 20 20:33 (:0.0) wesc pts/2 Jun 20 20:33 (:0.0) wesc pts/4 Jun 20 20:33 (:0.0) wesc pts/3 Jun 20 20:33 (:0.0) wesc pts/5 Jun 20 20:33 (:0.0) wesc pts/6 Jun 20 20:33 (:0.0) wesc pts/7 Jun 20 20:33 (:0.0) wesc pts/8 Jun 20 20:33 (:0.0)
利用linux的数据重定向,把who命令的输出重定向到一个文件中,然后在利用python分析这个文件。
import re f = open('whodata.txt', 'r') for eachLine in f.readlines(): print re.split(r'\s\s+', eachLine) f.close()
可以看到存在的一些问题:
1. 每一行的结尾都有一个回车符号,要去除这个东西。
2. 中间还有一个制表符\t,说明设计的正则表达式要修改。
3. 要直接从终端分析没一行,不要保存为本地文件在进行分析。
代码更新:
#! /usr/bin/python from os import popen from re import split f = popen('who', 'r') for eachLine in f.readlines(): print split(r'\s\s+|\t', eachLine.strip()) f.close()
其中strip函数介绍:
函数原型
声明:s为字符串,rm为要删除的字符序列
s.strip(rm) 删除s字符串中开头、结尾处,位于 rm删除序列的字符
s.lstrip(rm) 删除s字符串中开头处,位于 rm删除序列的字符
s.rstrip(rm) 删除s字符串中结尾处,位于 rm删除序列的字符
注意:
1. 当rm为空时,默认删除空白符(包括'\n', '\r', '\t', ' ')
例如:
2.这里的rm删除序列是只要边(开头或结尾)上的字符在删除序列内,就删除掉。
例如 :
相关文章推荐
- Python练习-- List Comprehensions
- 《笨办法学Python》 第43课手记
- Python导入matplotlib错误提示ImportError: matplotlib requires pyparsing
- Python socket超时
- 运行独立python 引用其他目录包
- python第七天
- Windows环境下新浪SAE本地开发环境搭建及简单测试
- os x + virtualenv + openCV2 + python2.7 环境打造
- 【LEETCODE】148- Sort List [Python]
- python 转化文件编码 utf8
- python之疑惑函数默认初始化
- [Leetcode]@python 95. Unique Binary Search Trees II
- cmd和python的mysql连接方法
- [Leetcode]@python 94. Binary Tree Inorder Traversal
- PyQt4 Python GUI窗体应用程序
- [Leetcode]@python 93. Restore IP Addresses
- python k-近邻算法
- Python练习-- slice
- Python练习-- loop
- Python练习-- list and tuple