20 模块之 re subprocess
re:
什么是正则:
- 正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。(在Python中)它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。
匹配示例:
- # =================================匹配模式=================================
- #一对一的匹配
- # 'hello'.replace(old,new)
- # 'hello'.find('pattern')
- #正则匹配
- import re
- #\w与\W
- print(re.findall('\w','hello egon 123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']
- print(re.findall('\W','hello egon 123')) #[' ', ' ']
- #\s与\S
- print(re.findall('\s','hello egon 123')) #[' ', ' ', ' ', ' ']
- print(re.findall('\S','hello egon 123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']
- #\n \t都是空,都可以被\s匹配
- print(re.findall('\s','hello \n egon \t 123')) #[' ', '\n', ' ', ' ', '\t', ' ']
- #\n与\t
- print(re.findall(r'\n','hello egon \n123')) #['\n']
- print(re.findall(r'\t','hello egon\t123')) #['\n']
- #\d与\D
- print(re.findall('\d','hello egon 123')) #['1', '2', '3']
- print(re.findall('\D','hello egon 123')) #['h', 'e', 'l', 'l', 'o', ' ', 'e', 'g', 'o', 'n', ' ']
- #\A与\Z
- print(re.findall('\Ahe','hello egon 123')) #['he'],\A==>^
- print(re.findall('123\Z','hello egon 123')) #['he'],\Z==>$
- #^与$
- print(re.findall('^h','hello egon 123')) #['h']
- print(re.findall('3$','hello egon 123')) #['3']
- # 重复匹配:| . | * | ? | .* | .*? | + | {n,m} |
- #.
- print(re.findall('a.b','a1b')) #['a1b']
- print(re.findall('a.b','a1b a*b a b aaab')) #['a1b', 'a*b', 'a b', 'aab']
- print(re.findall('a.b','a\nb')) #[]
- print(re.findall('a.b','a\nb',re.S)) #['a\nb']
- print(re.findall('a.b','a\nb',re.DOTALL)) #['a\nb']同上一条意思一样
- #*
- print(re.findall('ab*','bbbbbbb')) #[]
- print(re.findall('ab*','a')) #['a']
- print(re.findall('ab*','abbbb')) #['abbbb']
- #?
- print(re.findall('ab?','a')) #['a']
- print(re.findall('ab?','abbb')) #['ab']
- #匹配所有包含小数在内的数字
- print(re.findall('\d+\.?\d*',"asdfasdf123as1.13dfa12adsf1asdf3")) #['123', '1.13', '12', '1', '3']
- #.*默认为贪婪匹配
- print(re.findall('a.*b','a1b22222222b')) #['a1b22222222b']
- #.*?为非贪婪匹配:推荐使用
- print(re.findall('a.*?b','a1b22222222b')) #['a1b']
- #+
- print(re.findall('ab+','a')) #[]
- print(re.findall('ab+','abbb')) #['abbb']
- #{n,m}
- print(re.findall('ab{2}','abbb')) #['abb']
- print(re.findall('ab{2,4}','abbb')) #['abb']
- print(re.findall('ab{1,}','abbb')) #'ab{1,}' ===> 'ab+'
- print(re.findall('ab{0,}','abbb')) #'ab{0,}' ===> 'ab*'
- #[]
- print(re.findall('a[1*-]b','a1b a*b a-b')) #[]内的都为普通字符了,且如果-没有被转意的话,应该放到[]的开头或结尾
- print(re.findall('a[^1*-]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反,所以结果为['a=b']
- print(re.findall('a[0-9]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反,所以结果为['a=b']
- print(re.findall('a[a-z]b','a1b a*b a-b a=b aeb')) #[]内的^代表的意思是取反,所以结果为['a=b']
- print(re.findall('a[a-zA-Z]b','a1b a*b a-b a=b aeb aEb')) #[]内的^代表的意思是取反,所以结果为['a=b']
- #\# print(re.findall('a\\c','a\c')) #对于正则来说a\\c确实可以匹配到a\c,但是在python解释器读取a\\c时,会发生转义,然后交给re去执行,所以抛出异常
- print(re.findall(r'a\\c','a\c')) #r代表告诉解释器使用rawstring,即原生字符串,把我们正则内的所有符号都当普通字符处理,不要转义
- print(re.findall('a\\\\c','a\c')) #同上面的意思一样,和上面的结果一样都是['a\\c']
- #():分组
- print(re.findall('ab+','ababab123')) #['ab', 'ab', 'ab']
- print(re.findall('(ab)+123','ababab123')) #['ab'],匹配到末尾的ab123中的ab
- print(re.findall('(?:ab)+123','ababab123')) #findall的结果不是匹配的全部内容,而是组内的内容,?:可以让结果为匹配的全部内容
- print(re.findall('href="(.*?)"','<a href="http://www.baidu.com">点击</a>'))#['http://www.baidu.com']
- print(re.findall('href="(?:.*?)"','<a href="http://www.baidu.com">点击</a>'))#['href="http://www.baidu.com"']
- #|
- print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))
匹配模式
re提供的方法介绍
- # ===========================re模块提供的方法介绍===========================
- import re
- #
- print(re.findall('e','alex make love') ) #['e', 'e', 'e'],返回所有满足匹配条件的结果,放在列表里
- #
- print(re.search('e','alex make love').group()) #e,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。
- #
- print(re.match('e','alex make love')) #None,同search,不过在字符串开始处进行匹配,完全可以用search+^代替match
- #
- print(re.split('[ab]','abcd')) #['', '', 'cd'],先按'a'分割得到''和'bcd',再对''和'bcd'分别按'b'分割
- #
- print('===>',re.sub('a','A','alex make love')) #===> Alex mAke love,不指定n,默认替换所有
- print('===>',re.sub('a','A','alex make love',1)) #===> Alex make love
- print('===>',re.sub('a','A','alex make love',2)) #===> Alex mAke love
- print('===>',re.sub('^(\w+)(.*?\s)(\w+)(.*?\s)(\w+)(.*?)$',r'\5\2\3\4\1','alex make love')) #===> love make alex
- print('===>',re.subn('a','A','alex make love')) #===> ('Alex mAke love', 2),结果带有总共替换的个数
- #
- obj=re.compile('\d{2}')
- print(obj.search('abc123eeee').group()) #
- print(obj.findall('abc123eeee')) #['12'],重用了obj
- import re
- print(re.findall("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>")) #['h1']
- print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>").group()) #<h1>hello</h1>
- print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>").groupdict()) #<h1>hello</h1>
- print(re.search(r"<(\w+)>\w+</(\w+)>","<h1>hello</h1>").group())
- print(re.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>").group())
方法介绍
补充
- import re
- #使用|,先匹配的先生效,|左边是匹配小数,而findall最终结果是查看分组,所有即使匹配成功小数也不会存入结果
- #而不是小数时,就去匹配(-?\d+),匹配到的自然就是,非小数的数,在此处即整数
- #
- print(re.findall(r"-?\d+\.\d*|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))")) #找出所有整数['1', '-2', '60', '', '5', '-4', '3']
- #找到所有数字:
- print(re.findall('\D?(\-?\d+\.?\d*)',"1-2*(60+(-40.35/5)-(-4*3))")) # ['1','2','60','-40.35','5','-4','3']
- #计算器作业参考:http://www.cnblogs.com/wupeiqi/articles/4949995.html
- expression='1-2*((60+2*(-3-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'
- content=re.search('\(([\-\+\*\/]*\d+\.?\d*)+\)',expression).group() #(-3-40.0/5)
match:只检测re是不是在字符串开始的位置匹配,是的话返回对象,不是返回None
search:会浏览整个字符串查找匹配,匹配到一个就返回对象,没有就返回None
- #为何同样的表达式search与findall却有不同结果:
- print(re.search('\(([\+\-\*\/]*\d+\.?\d*)+\)',"1-12*(60+(-40.35/5)-(-4*3))").group()) #(-40.35/5)
- print(re.findall('\(([\+\-\*\/]*\d+\.?\d*)+\)',"1-12*(60+(-40.35/5)-(-4*3))")) #['/5', '*3']
- #看这个例子:(\d)+相当于(\d)(\d)(\d)(\d)...,是一系列分组
- print(re.search('(\d)+','').group()) #group的作用是将所有组拼接到一起显示出来
- print(re.findall('(\d)+','')) #findall结果是组内的结果,且是最后一个组的结果
search和findall
- #_*_coding:utf-8_*_
- __author__ = 'Linhaifeng'
- #在线调试工具:tool.oschina.net/regex/#
- import re
- s='''
- http://www.baidu.com
- egon@oldboyedu.com
- 你好
- 010-3141
- '''
- #最常规匹配
- # content='Hello 123 456 World_This is a Regex Demo'
- # res=re.match('Hello\s\d\d\d\s\d{3}\s\w{10}.*Demo',content)
- # print(res)
- # print(res.group())
- # print(res.span())
- #泛匹配
- # content='Hello 123 456 World_This is a Regex Demo'
- # res=re.match('^Hello.*Demo',content)
- # print(res.group())
- #匹配目标,获得指定数据
- # content='Hello 123 456 World_This is a Regex Demo'
- # res=re.match('^Hello\s(\d+)\s(\d+)\s.*Demo',content)
- # print(res.group()) #取所有匹配的内容
- # print(res.group(1)) #取匹配的第一个括号内的内容
- # print(res.group(2)) #去陪陪的第二个括号内的内容
- #贪婪匹配:.*代表匹配尽可能多的字符
- # import re
- # content='Hello 123 456 World_This is a Regex Demo'
- #
- # res=re.match('^He.*(\d+).*Demo$',content)
- # print(res.group(1)) #只打印6,因为.*会尽可能多的匹配,然后后面跟至少一个数字
- #非贪婪匹配:?匹配尽可能少的字符
- # import re
- # content='Hello 123 456 World_This is a Regex Demo'
- #
- # res=re.match('^He.*?(\d+).*Demo$',content)
- # print(res.group(1)) #只打印6,因为.*会尽可能多的匹配,然后后面跟至少一个数字
- #匹配模式:.不能匹配换行符
- content='''Hello 123456 World_This
- is a Regex Demo
- '''
- # res=re.match('He.*?(\d+).*?Demo$',content)
- # print(res) #输出None
- # res=re.match('He.*?(\d+).*?Demo$',content,re.S) #re.S让.可以匹配换行符
- # print(res)
- # print(res.group(1))
- #转义:\
- # content='price is $5.00'
- # res=re.match('price is $5.00',content)
- # print(res)
- #
- # res=re.match('price is \$5\.00',content)
- # print(res)
- #总结:尽量精简,详细的如下
- # 尽量使用泛匹配模式.*
- # 尽量使用非贪婪模式:.*?
- # 使用括号得到匹配目标:用group(n)去取得结果
- # 有换行符就用re.S:修改模式
- #re.search:会扫描整个字符串,不会从头开始,找到第一个匹配的结果就会返回
- # import re
- # content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
- #
- # res=re.match('Hello.*?(\d+).*?Demo',content)
- # print(res) #输出结果为None
- #
- # import re
- # content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
- #
- # res=re.search('Hello.*?(\d+).*?Demo',content) #
- # print(res.group(1)) #输出结果为
- #re.search:只要一个结果,匹配演练,
- import re
- content='''
- <tbody>
- <tr id="4766303201494371851675" class="even "><td><div class="hd"><span class="num">1</span><div class="rk "><span class="u-icn u-icn-75"></span></div></div></td><td class="rank"><div class="f-cb"><div class="tt"><a href="/song?id=476630320"><img class="rpic" src="http://p1.music.126.net/Wl7T1LBRhZFg0O26nnR2iQ==/19217264230385030.jpg?param=50y50&quality=100"></a><span data-res-id="476630320" "
- # res=re.search('<a\shref=.*?<b\stitle="(.*?)".*?b>',content)
- # print(res.group(1))
- #re.findall:找到符合条件的所有结果
- # res=re.findall('<a\shref=.*?<b\stitle="(.*?)".*?b>',content)
- # for i in res:
- # print(i)
- #re.sub:字符串替换
- import re
- content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
- # content=re.sub('\d+','',content)
- # print(content)
- #用\1取得第一个括号的内容
- #用法:将123与456换位置
- # import re
- # content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
- #
- # # content=re.sub('(Extra.*?)(\d+)(\s)(\d+)(.*?strings)',r'\1\4\3\2\5',content)
- # content=re.sub('(\d+)(\s)(\d+)',r'\3\2\1',content)
- # print(content)
- # import re
- # content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
- #
- # res=re.search('Extra.*?(\d+).*strings',content)
- # print(res.group(1))
- # import requests,re
- # respone=requests.get('https://book.douban.com/').text
- # print(respone)
- # print('======'*1000)
- # print('======'*1000)
- # print('======'*1000)
- # print('======'*1000)
- # res=re.findall('<li.*?cover.*?href="(.*?)".*?title="(.*?)">.*?more-meta.*?author">(.*?)</span.*?year">(.*?)</span.*?publisher">(.*?)</span.*?</li>',respone,re.S)
- # # res=re.findall('<li.*?cover.*?href="(.*?)".*?more-meta.*?author">(.*?)</span.*?year">(.*?)</span.*?publisher">(.*?)</span>.*?</li>',respone,re.S)
- #
- #
- # for i in res:
- # print('%s %s %s %s' %(i[0].strip(),i[1].strip(),i[2].strip(),i[3].strip()))
了解
subprocess模块
subprocess模块
sub 子
process 进程
什么是进程
正在进行中的程序 每当打开一个程序就会开启一个进程
每个进程包含运行程序所需的所有资源
正常情况下 不可以跨进程访问数据
但是有些情况写就需要访问别的进程数据 提供一个叫做管道的对象 专门用于跨进程通讯
作用:用于执行系统命令
常用方法
run 返回一个表示执行结果的对象
call 返回的执行的状态码
总结 subprocess的好处是可以获取指令的执行结果
subprocess执行指令时 可以在子进程中 这样避免造成主进程卡死
import subprocess
# print(1)
# res = subprocess.run("tasklist",shell=True,stdout=subprocess.PIPE)
#
# print("=====================================================")
# print(res.stdout.decode("gbk"))
#
# print(res.stderr)
# res = subprocess.call("tasklist",shell=True)
# print(res)
# 第一个进程a读取tasklist的内容 将数据交给另一个进程b 进程b将数据写到文件中
res1 = subprocess.Popen("tasklist",stdout=subprocess.PIPE,shell=True,stderr=subprocess.PIPE)
# print("hello")
# print(res1.stdout.read().decode("gbk"))
# print(res1.stderr.read().decode("gbk"))
#
# res2 = subprocess.Popen("findstr cmd",stdout=subprocess.PIPE,shell=True,stderr=subprocess.PIPE,stdin=res1.stdout)
# print(res2.stdout.read().decode("gbk"))
res2 = subprocess.Popen("echo >a.txt", stdout=subprocess.PIPE, shell=True, stderr=subprocess.PIPE,stdin=res1.stdout)
print(res2.stdout.read().decode("gbk"))
res1=subprocess.Popen(r'',shell=True,stdout=subprocess.PIPE)
res=subprocess.Popen('findstr test*',shell=True,stdin=res1.stdout,stdout=subprocess.PIPE)
print(res.stdout.read().decode('gbk'))
20 模块之 re subprocess的更多相关文章
- python 常用模块 time random os模块 sys模块 json & pickle shelve模块 xml模块 configparser hashlib subprocess logging re正则
python 常用模块 time random os模块 sys模块 json & pickle shelve模块 xml模块 configparser hashlib subprocess ...
- Python模块之OS,subprocess
1.os 模块 简述: os 表示操作系统 该模块主要用来处理与系统相关操作 最常用的是文件操作 打开 获取 写入 删除 复制 重命名 常用操作 os.getcwd() : 返回当前文件所在文件夹路径 ...
- Python中模块之logging & subprocess的讲解
subprocess & logging模块的介绍 1. subprocess 该模块替代了os.system & os.pawn*所实现的功能. 2. logging 1. 日志五大 ...
- 常用模块之hashlib,subprocess,logging,re,collections
hashlib 什么是hashlib 什么叫hash:hash是一种算法(3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,M ...
- python基础-7.3模块 configparser logging subprocess os.system shutil
1. configparser模块 configparser用于处理特定格式的文件,其本质上是利用open来操作文件. 继承至2版本 ConfigParser,实现了更多智能特征,实现更有可预见性,新 ...
- python3+ 模块学习 之 subprocess
subprocess 模块方法: call() check_call() check_output() 以上三个方法用于创建一个子进程,父进程等待子进程结束.若shell = true, 则shell ...
- python模块 os&sys&subprocess&hashlib模块
os模块 # os模块可根据带不带path分为两类 # 不带path print(os.getcwd()) # 得到当前工作目录 print(os.name) # 指定你正在使用的操作系统,windo ...
- python模块struct和subprocess
准确地讲,Python没有专门处理字节的数据类型.但由于str既是字符串,又可以表示字节,所以,字节数组=str.而在C语言中,我们可以很方便地用struct.union来处理字节,以及字节和int, ...
- 【python库模块】Python subprocess模块功能与常见用法实例详解
前言 这篇文章主要介绍了Python subprocess模块功能与常见用法,结合实例形式详细分析了subprocess模块功能.常用函数相关使用技巧. 参考 1. Python subprocess ...
随机推荐
- jumpserver-1.4.0.2
关闭防火墙和selinux IP:192.168.199.115 一. 准备 Python3 和 Python 虚拟环境 yum -y install wget sqlite-devel xz gcc ...
- beanstalkd 说明文档
BEANSTALKD(1) BEANSTALKD(1) NAME beanstalkd - simple, fast work queue SYNOPSIS beanstalkd [options] ...
- pta l2-14(列车调度)
题目链接:https://pintia.cn/problem-sets/994805046380707840/problems/994805063166312448 题意:给定n个数的重排列,求至少需 ...
- [1.16更新B14特征处理]津南数字制造题目解读及部分思路~~有趣的特征
[1.16更新B14特征处理]津南数字制造题目解读及部分思路--有趣的特征 Article onion啦啦啦 2019-01-17 16:03:38 11 1790 11 首先声明,我并不能保证这些特 ...
- Shell教程 之流程控制
1. if else 1.1 if if语句语法格式: if condition then command1 command2 ... commandN fi 写成一行(适用于终端命令提示符): if ...
- .linearDrag on rigidbody / rigidbody2D in code?
it's rigidbody.drag not .linearDrag 这几天在做一个弹球的游戏,发现小球落下后不会自动停,测试后发现线性阻尼增加后可以 于是加了个触发器不停增加线性阻尼值 priva ...
- SpringBoot08 请求方式、参数获取注解、参数验证、前后台属性名不一致问题、自定义参数验证注解、BeanUtils的使用
1 请求方式 在定义一个Rest接口时通常会利用GET.POST.PUT.DELETE来实现数据的增删改查:这几种方式有的需要传递参数,后台开发人员必须对接收到的参数进行参数验证来确保程序的健壮性 1 ...
- fnb2b分支拉取注意事项
1. 大B分支拉取以后不要忘记把index.php中dev环境改为 $save_url = "http://dev-b2b.dev1.fn/"; 2. 大B分支拉取后,记得/bas ...
- swift - VC添加手势返回
1.需要添加手势的界面 (1)addBackGesture() (2) 设置手势返回代理 // MARK: - 添加返回手势 extension JYRTSShopDetialConteoller:U ...
- cherry-pick 命令
拣选会提取某次提交的补丁,之后尝试将其重新应用到当前分支上. 这种方式在你只想引入特性分支中的某个提交时很有用. 假设你的项目提交历史如下: 如果你希望将提交 e43a6 拉取到 master 分支, ...