一、
1.绝对路径的读取
通过编码格式来读取文件中的中文
foo=open(R'D:\python项目\记事本.txt','r+',encoding='utf-8')#编码格式必须与文件的编码格式一致 R:去掉特殊符
text=foo.read()
print(text)
2.文件读取得其他方法:
readline():读取一行,直到一行结束
foo=open(R'D:\python项目\记事本.txt','r+',encoding='utf-8')
#循环读取 以行为单位 读取全部内容
text=foo.readline()
while len(text)!=0:
print(text)
text = foo.readline()
执行命令得
1.python---java
2.python---java
3.python---java
readlines():多行读取
foo=open(R'D:\python项目\记事本.txt','r+',encoding='utf-8')
fjava=open('D:\python项目\java记事本.txt','w+',encoding='utf-8')
text=foo.readlines()
print(text)
for li in text:
fjava.write(li.replace('python','java'))#将读取到的python换为java 并且写入fjava文件中
print(li)
print(type(text)) #<class 'list'>
print(len(text)) # 以行为单位: 输出为 3
foo.close()
fjava.close()
print('复制并替换完成')
执行命令得
['\ufeff\ufeff1.python---java\n', '2.python---java\n', '3.python---java']
1.python---java
2.python---java
3.python---java
<class 'list'>
3
复制并替换完成
二、类似爬虫
模拟浏览器获得源代码爬所需要的东西
源代码的获取
from urllib import request
#请求(request)打开一个url
response=request.urlopen('https://www.baidu.com/')
#在本地创建一个文件
xm=open('baidu.txt','w',encoding='utf-8')
#读取网页中的源代码 并写入新创建的文件中
txt=response.read()
xm.write(str(txt.decode()))
xm.close()
执行命令得
#baidu.txt文件中
<html>
<head>
<script>
location.replace(location.href.replace("https://","http://"));
</script>
</head>
<body>
<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>
</body>
</html>
三、XML(EXtensible Markup Language),可扩展标记语言
1.特点:XML与操作系统 编程语言的开发平台无关
实现不同系统之间的数据交换
2.作用:数据交换
配置应用程序和网站
3.XML文档内容由一系列标签元素组成
<元素名 属性名='属性值'>元素内容</元素名>
属性值用双引号包裹
一个元素可以有多个属性
属性值中不能直接包含<、"、&(不建议: ' >)
4.标签编写注意事项
所有XML元素都必须有结束标签
XML标签对大小写敏感
XML必须正确嵌套
同级标签以缩进对齐
元素名称可以包含字母 数字或其他的字符
元素名称不能以数字或者标点符号开始
元素名称中不能含空格
5.Python中提供的XML解析方式:
方法 | 特点 |
SAX | SAX解析通过流模式在解析XML的过程中触发对应的事件(start_element、char_data、end_element)并调用用户定义的回调函数来处理XML文件。 |
DOM | 将XML数据在内存中解析成一个树,通过对树的操作来操作XML,占用内存大,解析速度较慢,优点是可以任意遍历树的节点。 |
ElementTree | 类似一个轻量级的DOM,也是本篇文章主要介绍的。 |
6.准备一份XML格式的文件(文件名为lianxi.xml)
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
7.XML格式介绍
<tag attrib = > text </tag> tail
例:<APP_KEY channel = 'CSDN'> hello123456789 </APP_KEY>
- tag,即标签,用于标识该元素表示哪种数据,即APP_KEY
- attrib,即属性,用Dictionary形式保存,即{'channel' = 'CSDN'}
- text,文本字符串,可以用来存储一些数据,即hello123456789
- tail,尾字符串,并不是必须的,例子中没有包含。
7.ElementTree解析XML文件的过程:
导入ElementTree,import xml.etree.ElementTree as ET
解析XML文件找到根节点
直接捷信XML文件并获得根节点:tree=ET.parse('country_datat.xml') root=tree.getroot()
解析字符串: root=ET.fromstring(country_datat_as_string)
遍历根节点可以获得子节点,然后就可以根据要求拿到需要的字段了
源码演示:
import xml.etree.ElementTree as ET
#1.先加载文档到内存里 形成一个倒桩的树结构
tree=ET.parse('lianxi.xml')
#2.获取根节点
root=tree.getroot()
print('root-tag:',root.tag,'root-attrib:',root.attrib,'root-text:',root.text)
for child in root:
print('child-tag:',child.tag,'child-attrib:',child.attrib,'child-text:',child.text)
for sub in child:
print('sub-tag是:', sub.tag, ',sub.attrib:', sub.attrib, ',sub.text:', sub.text)
执行命令得
root-tag: data root-attrib: {} root-text:
child-tag: country child-attrib: {'name': 'Liechtenstein'} child-text:
sub-tag是: rank ,sub.attrib: {} ,sub.text: 1
sub-tag是: year ,sub.attrib: {} ,sub.text: 2008
sub-tag是: gdppc ,sub.attrib: {} ,sub.text: 141100
sub-tag是: neighbor ,sub.attrib: {'name': 'Austria', 'direction': 'E'} ,sub.text: None
sub-tag是: neighbor ,sub.attrib: {'name': 'Switzerland', 'direction': 'W'} ,sub.text: None
child-tag: country child-attrib: {'name': 'Singapore'} child-text:
sub-tag是: rank ,sub.attrib: {} ,sub.text: 4
sub-tag是: year ,sub.attrib: {} ,sub.text: 2011
sub-tag是: gdppc ,sub.attrib: {} ,sub.text: 59900
sub-tag是: neighbor ,sub.attrib: {'name': 'Malaysia', 'direction': 'N'} ,sub.text: None
child-tag: country child-attrib: {'name': 'Panama'} child-text:
sub-tag是: rank ,sub.attrib: {} ,sub.text: 68
sub-tag是: year ,sub.attrib: {} ,sub.text: 2011
sub-tag是: gdppc ,sub.attrib: {} ,sub.text: 13600
sub-tag是: neighbor ,sub.attrib: {'name': 'Costa Rica', 'direction': 'W'} ,sub.text: None
sub-tag是: neighbor ,sub.attrib: {'name': 'Colombia', 'direction': 'E'} ,sub.text: None
8.查找节点
当XML文件较大或者其中的子节点tag非常多的时候,一个一个获取是比较麻烦的而且有很多我们不要的,这样就可以通过find('nodeName')或者findall('nodeName')方法来查找指定的节点
find('nodeName'):表示在该节点下,查找其中第一个tag为nodeName的节点。
findall('nodeName'):表示在该节点下,查找其中所有tag为nodeName的节点
import xml.etree.ElementTree as ET
tree=ET.parse('lianxi.xml')
root=tree.getroot()
animNode=root.find('country')#查找root节点下第一个tag为country得节点
print(animNode.tag,animNode.attrib,animNode.text)
执行命令得
country {'name': 'Liechtenstein'}
9.删除指定的节点以及保存
在合并Manifest文件的时候,可能有一些重复的权限,那么怎么删除掉呢,删除指定节点可以通过remove(node)方法,移除指定的节点。
删除属性name为Liechtenstein节点
import xml.etree.ElementTree as ET
tree=ET.parse('lianxi.xml')
root=tree.getroot()
animNode=root.find('country')#查找root节点下第一个tag为country得节点
print(animNode.tag,animNode.attrib,animNode.text)
if animNode.attrib['name'] =='Liechtenstein':
root.remove(animNode)
tree.write('lianxi.xml')#保存修改后的XML文件
执行命令得
<data>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor direction="N" name="Malaysia" />
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor direction="W" name="Costa Rica" />
<neighbor direction="E" name="Colombia" />
</country>
</data>
三、XML解析器 体系结构和API
Python标准库提供了一组极少使用但有用的接口来处理XML.两个基本和最广泛使用在XML数据的API是SAX 和XDOM接口
简单的XML(SAX) 在这里,注册感兴趣的时间回调,然后让解析器继续执行文档.当文档较大或存在内存限制时,此功能非常有用,它会从文件读取文件时解析文件,并且整个文件不会储存在内存中.
文档对象模型(DOM)API这是一个万维网联盟的推荐,它将整个文件读入储存起并以分层(基于树)得形式存储,以表示XML文档的所有功能
当处理大文件时,SAX显然无法与DOM一样快地处理信息。 另一方面,使用DOM专门可以真正地占用资源,特别是如果要加许多文件使用的时候。
对于我们所有的XML代码示例,使用一个简单的XML文件:movies.xml作为输入 -
<?xml version="1.0" encoding="utf-8" ?>
<collection shelf = "New Arrivals">
<movie title = "Enemy Behind">
<type>War, Thriller</type>
<format>DVD</format>
<year>2013</year>
<rating>PG</rating>
<stars>10</stars>
<description>Talk about a US-Japan war</description>
</movie>
<movie title = "Transformers">
<type>Anime, Science Fiction</type>
<format>DVD</format>
<year>1989</year>
<rating>R</rating>
<stars>8</stars>
<description>A schientific fiction</description>
</movie>
<movie title = "Trigun">
<type>Anime, Action</type>
<format>DVD</format>
<episodes>4</episodes>
<rating>PG</rating>
<stars>10</stars>
<description>Vash the Stampede!</description>
</movie>
<movie title = "Ishtar">
<type>Comedy</type>
<format>VHS</format>
<rating>PG</rating>
<stars>2</stars>
<description>Viewable boredom</description>
</movie>
</collection>
SAX是事件驱动的XML解析的标准接口。 使用SAX解析XML通常需要通过子类化xml.sax.ContentHandler
来创建自己的ContentHandler
。ContentHandler
处理XML样式/风格的特定标签和属性。 ContentHandler
对象提供了处理各种解析事件的方法。它拥有的解析器在解析XML文件时调用ContentHandler
方法。
在XML文件的开头和结尾分别调用:startDocument
和endDocument
方法。 characters(text)
方法通过参数text
传递XML文件的字符数据。
ContentHandler
在每个元素的开头和结尾被调用。如果解析器不在命名空间模式下,则调用startElement(tag,attributes)
和endElement(tag)
方法; 否则,调用相应的方法startElementNS
和endElementNS
方法。 这里,tag
是元素标签,属性是Attributes
对象。
以下是继续前面了解的其他重要方法 -
parse()方法
以下方法创建一个SAX解析器并使用它来解析文档
xml.sax.parse( xmlfile, contenthandler[, errorhandler])
以下是参数的详细信息 -
- xmlfile - 这是要读取的XML文件的名称。
- contenthandler - 这必须是
ContentHandler
对象。 - errorhandler - 如果指定,
errorhandler
必须是SAX ErrorHandler
import xml.sax
class MovieHandler(xml.sax.ContentHandler):
def __init__(self):
self.CurrentData = ""#当前读取的对象节点属性
self.type = ""
self.format = ""
self.year = ""
self.rating = ""
self.stars = ""
self.description = ""
def startElement(self, tag, attributes):
self.CurrentData = tag
if tag == "movie":
print ("*****Movie*****")
title = attributes["title"]
print ("Title:", title)
# Call when an elements ends
def endElement(self, tag):
if self.CurrentData == "type":
print ("Type:", self.type)
elif self.CurrentData == "format":
print ("Format:", self.format)
elif self.CurrentData == "year":
print ("Year:", self.year)
elif self.CurrentData == "rating":
print ("Rating:", self.rating)
elif self.CurrentData == "stars":
print ("Stars:", self.stars)
elif self.CurrentData == "description":
print ("Description:", self.description)
self.CurrentData = ""
# Call when a character is read
def characters(self, content):#传递
if self.CurrentData == "type":
self.type = content
elif self.CurrentData == "format":
self.format = content
elif self.CurrentData == "year":
self.year = content
elif self.CurrentData == "rating":
self.rating = content
elif self.CurrentData == "stars":
self.stars = content
elif self.CurrentData == "description":
self.description = content
if ( __name__ == "__main__"):
# create an XMLReader
parser = xml.sax.make_parser()
# turn off namepsaces 工作目录
parser.setFeature(xml.sax.handler.feature_namespaces, 0)
# override the default ContextHandler
Handler = MovieHandler()
parser.setContentHandler( Handler )
parser.parse("movie.xml")
执行命令
*****Movie*****
Title: Enemy Behind
Type: War, Thriller
Format: DVD
Year: 2013
Rating: PG
Stars: 10
Description: Talk about a US-Japan war
*****Movie*****
Title: Transformers
Type: Anime, Science Fiction
Format: DVD
Year: 1989
Rating: R
Stars: 8
Description: A schientific fiction
*****Movie*****
Title: Trigun
Type: Anime, Action
Format: DVD
Rating: PG
Stars: 10
Description: Vash the Stampede!
*****Movie*****
Title: Ishtar
Type: Comedy
Format: VHS
Rating: PG
Stars: 2
Description: Viewable boredom