4月9日 python学习总结 模块
1、XML模块
xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。
xml的格式,就是通过<>节点来区别数据结构的
xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml:
- # print(root.iter('year')) #全文搜索
- # print(root.find('country')) #在root的子节点找,只找一个
- # print(root.findall('country')) #在root的子节点找,找所有
- import xml.etree.ElementTree as ET
- tree = ET.parse("xmltest.xml")
- root = tree.getroot()
- print(root.tag)
- #遍历xml文档
- for child in root:
- print('========>',child.tag,child.attrib,child.attrib['name'])
- for i in child:
- print(i.tag,i.attrib,i.text)
- #只遍历year 节点
- for node in root.iter('year'):
- print(node.tag,node.text)
- #---------------------------------------
- import xml.etree.ElementTree as ET
- tree = ET.parse("xmltest.xml")
- root = tree.getroot()
- #修改
- for node in root.iter('year'):
- new_year=int(node.text)+1
- node.text=str(new_year)
- node.set('updated','yes')
- node.set('version','1.0')
- tree.write('test.xml')
- #删除node
- for country in root.findall('country'):
- rank = int(country.find('rank').text)
- if rank > 50:
- root.remove(country)
- tree.write('output.xml')
- #在country内添加(append)节点year2
- import xml.etree.ElementTree as ET
- tree = ET.parse("a.xml")
- root=tree.getroot()
- for country in root.findall('country'):
- for year in country.findall('year'):
- if int(year.text) > 2000:
- year2=ET.Element('year2')
- year2.text='新年'
- year2.attrib={'update':'yes'}
- country.append(year2) #往country节点下添加子节点
- tree.write('a.xml.swap')
- import xml.etree.ElementTree as ET
- new_xml = ET.Element("namelist")
- name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
- age = ET.SubElement(name,"age",attrib={"checked":"no"})
- sex = ET.SubElement(name,"sex")
- sex.text = '33'
- name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
- age = ET.SubElement(name2,"age")
- age.text = '19'
- et = ET.ElementTree(new_xml) #生成文档对象
- et.write("test.xml", encoding="utf-8",xml_declaration=True)
- ET.dump(new_xml) #打印生成的格式
2、re模块
正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。(在Python中)它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。
生活中处处都是正则:
比如我们描述:4条腿
你可能会想到的是四条腿的动物或者桌子,椅子等
继续描述:4条腿,活的
就只剩下四条腿的动物这一类了
应用:
- # =================================匹配模式=================================
- #一对一的匹配
- # '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模块提供的方法介绍===========================
- import re
- #1
- print(re.findall('e','alex make love') ) #['e', 'e', 'e'],返回所有满足匹配条件的结果,放在列表里
- #2
- print(re.search('e','alex make love').group()) #e,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。
- #3
- print(re.match('e','alex make love')) #None,同search,不过在字符串开始处进行匹配,完全可以用search+^代替match
- #4
- print(re.split('[ab]','abcd')) #['', '', 'cd'],先按'a'分割得到''和'bcd',再对''和'bcd'分别按'b'分割
- #5
- 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),结果带有总共替换的个数
- #6
- obj=re.compile('\d{2}')
- print(obj.search('abc123eeee').group()) #12
- 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())
- 补充一
4月9日 python学习总结 模块的更多相关文章
- 4月8日 python学习总结 模块与包
一.包 #官网解释 Packages are a way of structuring Python's module namespace by using "dotted module n ...
- 4月10日 python学习总结 模块和面向对象
1.hashlib 1.什么叫hash:hash是一种算法,该算法接受传入的内容,经过运算得到一串hash值 2.hash值的特点是:2.1 只要传入的内容一样,得到的hash值必然一样=====& ...
- 4月2日 python学习总结
昨天内容回顾: 1.迭代器 可迭代对象: 只要内置有__iter__方法的都是可迭代的对象 既有__iter__,又有__next__方法 调用__iter__方法==>得到内置的迭代器对象 调 ...
- 4月12日 python学习总结 继承和派生
一.继承 什么是继承: 继承是一种新建类的方式,在python中支持一个子类继承多个父类 新建类称为子类或派生类 父类可以称之为基类或者超类 子类会遗传父类的属性 2. 为什么继承 ...
- 4月11日 python学习总结 对象与类
1.类的定义 #类的定义 class 类名: 属性='xxx' def __init__(self): self.name='enon' self.age=18 def other_func: pas ...
- 6月4日 python学习总结 初次接触jQuery
1. jQuery是什么?是一个轻量级的,兼容多浏览器的JS库(write less, do more) 1. 是一个工具,简单方便的实现一些DOM操作 2. 不用jQuery完全可以,但是不明智. ...
- 5月16日 python学习总结 DBUtils模块、orm 和 cookie、session、token
一.DBUtils模块 介绍 The DBUtils suite is realized as a Python package containing two subsets of modules, ...
- 5月11日 python学习总结 子查询、pymysql模块增删改查、防止sql注入问题
一.子查询 子查询:把一个查询语句用括号括起来,当做另外一条查询语句的条件去用,称为子查询 select emp.name from emp inner join dep on emp.dep_id ...
- 4月19日 python学习总结 套接字模块的使用
服务端: import socket phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 买电话 phone.bind(('127.0.0 ...
随机推荐
- docker | jenkins 实现自动化CI/CD,后端躺着把运维的钱挣了!(下)
前言 在上一篇文章中,我们使用docker编写Dockerfile文件,将我们自己的项目构建成镜像,然后发布到Docker Hub中,并且用自己的云服务器拉取Docker Hub上我们自己上传的项目镜 ...
- Oracle 获取表注释和列注释
全部表 select table_name from user_tables; //当前用户拥有的表 select table_name from all_tables; //所有用户的表 selec ...
- 基于GDAL库,读取.grd文件(以海洋地形数据为例)C++版
技术背景 海洋地形数据主要是通过美国全球地形起伏数据(GMT)获得,数据格式为grd(GSBG)二进制数据,打开软件通过是Surfer软件,surfer软件可进行数据的编辑处理,以及进一步的可视化表达 ...
- 在这个插件帮助下,终于用上免费的Https协议外链的图床了
前天,强哥发了一篇推文,讲述了应该如何免费且快速的生成自己的博客网站: 期间也有提到一点就是我们在写博客的时候,因为使用的是Markdown格式的文件,而如果想要Markdown格式的文件在图片上传 ...
- CPU优化上下文切换之线程上下文切换案例分析
对于线程上下文切换,如果同进程内就是只是线程上下文切换,如果非同进程内则是进程上下文切换.下面进行线程上下文切换场景模拟. 一.环境准备~模拟工具sysbench. 1)安装git yum -y in ...
- Https原理与演变
巨人的肩膀 为了一个HTTPS,浏览器操碎了心··· (qq.com)
- mysql 去除前后空白字符
update table set field = replace(replace(replace(field,char(9),''),char(10),''),char(13),'');
- 使用讯飞tts+ffmpeg自动生成视频
参考 FFmpeg 讯飞离线语音合成 起因 某日,看到一个营销号的视频说做视频日进斗金,大意是用软件识别文章小说,搭配一些图片转换成自己的视频.看完当时脑海里冒出一个念头,我也可以,于是有了这番尝试. ...
- scrapy初体验
1. 构建scrapy项目 scrapy startproject ['项目名'] 在spiders下生成文件 cd spiders scrapy genspider douban_spider [' ...
- 【C# 线程】 volatile 关键字和Volatile类、Thread.VolatileRead|Thread.VolatileWrite 详细 完整
overview 同步基元分为用户模式和内核模式 用户模式:Iterlocked.Exchange(互锁).SpinLocked(自旋锁).易变构造(volatile关键字.volatile类.Thr ...