当前位置:首页 » 编程语言 » pythonxml字符串

pythonxml字符串

发布时间: 2022-12-27 05:44:51

A. 利用python编程,在多个打包压缩的文件中搜索指定字符串。有很多xml文件

ziprar.py

__author__='williezh'
#!/usr/bin/envpython3

importos
importsys
importtime
importshutil
importzipfile
fromzipfileimportZIP_DEFLATED


#Zip文件处理类
classZFile(object):
def__init__(self,fname,mode='r',basedir=''):
self.fname=fname
self.mode=mode
ifself.modein('w','a'):
self.zfile=zipfile.ZipFile(fname,mode,compression=ZIP_DEFLATED)
else:
self.zfile=zipfile.ZipFile(fname,self.mode)
self.basedir=basedir
ifnotself.basedir:
self.basedir=os.path.dirname(fname)

defaddfile(self,path,arcname=None):
path=path.replace('//','/')
ifnotarcname:
ifpath.startswith(self.basedir):
arcname=path[len(self.basedir):]
else:
arcname=''
self.zfile.write(path,arcname)

defaddfiles(self,paths):
forpathinpaths:
ifisinstance(path,tuple):
self.addfile(*path)
else:
self.addfile(path)

defclose(self):
self.zfile.close()

defextract_to(self,path):
forpinself.zfile.namelist():
self.extract(p,path)

defextract(self,fname,path):
ifnotfname.endswith('/'):
fn=os.path.join(path,fname)
ds=os.path.dirname(fn)
ifnotos.path.exists(ds):
os.makedirs(ds)
withopen(fn,'wb')asf:
f.write(self.zfile.read(fname))


#创建Zip文件
defcreateZip(zfile,files):
z=ZFile(zfile,'w')
z.addfiles(files)
z.close()


#解压缩Zip到指定文件夹
defextractZip(zfile,path):
z=ZFile(zfile)
z.extract_to(path)
z.close()


#解压缩rar到指定文件夹
defextractRar(zfile,path):
rar_command1="WinRAR.exex-ibck%s%s"%(zfile,path)
rar_command2=r'"C:WinRAR.exe"x-ibck%s%s'%(zfile,path)
try:
res=os.system(rar_command1)
ifres==0:
print("PathOK.")
except:
try:
res=os.system(rar_command2)
ifres==0:
print("Successtounrarthefile{}.".format(path))
except:
print('Error:cannotunrarthefile{}'.format(path))


#解压多个压缩文件到一个临时文件夹
defextract_files(file_list):
newdir=str(int(time.time()))
forfninfile_list:
subdir=os.path.join(newdir,fn)
ifnotos.path.exists(subdir):
os.makedirs(subdir)
iffn.endswith('.zip'):
extractZip(fn,subdir)
eliffn.endswith('.rar'):
extractRar(fn,subdir)
returnnewdir


#查找一个文件夹中的某些文件,返回文件内容包含findstr_list中所有字符串的文件
deffindstr_at(basedir,file_list,findstr_list):
files=[]
forr,ds,fsinos.walk(basedir):
forfninfs:
iffninfile_list:
withopen(os.path.join(r,fn))asf:
s=f.read()
ifall(iinsforiinfindstr_list):
files.append(os.path.join(r,fn))
returnfiles


if__name__=='__main__':
files=[iforiinsys.argv[1:]ifnoti.startswith('-')]
unzipfiles=[iforiinfilesifi.endswith('.zip')ori.endswith('.rar')]
xmlfiles=[iforiinfilesifi.endswith('.xml')]
save_unzipdir=Trueif'-s'insys.argvelseFalse
findstr=[i.split('=')[-1]foriinsys.argvifi.startswith('--find=')]
findstring=','.join(['`{}`'.format(i)foriinfindstr])
newdir=extract_files(unzipfiles)
result=findstr_at(newdir,xmlfiles,findstr)
ifnotresult:
msg='Noneofthefile(s)containthegivenstring{}.'
print(msg.format(findstring))
else:
msg='{}file(s)containthegivenstring{}:'
print(msg.format(len(result),findstring))
print(' '.join([i.replace(newdir+os.sep,'')foriinsorted(result)]))

ifnotsave_unzipdir:
shutil.rmtree(newdir)
$python3ziprar.pyaaa.zipaaa2.zipaaa3.zipaaa.xmlaaa1.xmlaaa2.xml--find="Itwas"--find="when"
Noneofthefile(s)containthegivenstring`Itwas`,`when`.
$python3ziprar.pyaaa.zipaaa2.zipaaa3.zipaaa.xmlaaa1.xmlaaa2.xml--find="Itwas"--find="I"
2file(s)containthegivenstring`Itwas`,`I`:
aaa.zip/aaa2.xml
aaa2.zip/aaa2.xml
$python3ziprar.pyaaa.zipaaa2.zipaaa3.zipaaa.xmlaaa1.xmlaaa2.xml--find="Itwas"
2file(s)containthegivenstring`Itwas`:
aaa.zip/aaa2.xml
aaa2.zip/aaa2.xml

B. python判断一个字符是否是xml合法字符

#假如你的某些字符是s和asome_letter = ["s","a"]ss = "sadsahchcdsc"other_letters = []for s in ss: if not some_letter.count(s): other_letters.append(s) flag = Trueif other_letters: print "字符串含有别的字符",other_letters

C. python 如何把xml文件转化成string

你说的不是xml文件吧,是xml对象转化成string吧。

你可以使用toxml()这个方法。

Node.toxml([encoding])
"""
.
Withnoargument,,andtheresultis

document.-8islikely
incorrect,sinceUTF-8isthedefaultencodingofXML.
Withanexplicitencoding[1]argument,theresultisabytestringinthe
specifiedencoding..To
,the
“utf-8”.
Changedinversion2.3:;seewritexml().
"""

如果解决了您的问题请采纳!
如果未解决请继续追问

D. Python 怎么解析 xml字符串

1. 我上面这段xml代码,一开始没有注意看,在每一个元素的结尾元素中都含有转义符,这就是为什么我用xml解析插件时一直保报错的原因,因为他不是正规的xml格式。我的方法是用正则替换掉:re.sub(r'(<)\\(/.+?>)',r'\g<1>\g<2>',f_xml) 对于Python中的正则re的sub用法
2. 处理成正规的xml格式后,我这里还是用ElementTree来解析的,但在加载时又报错:
cElementTree.ParseError: XML or text declaration not at start of entity: line 2, column 0
这个错误我在网上没有找到合适的答案,不过根据字面意思来解决,就是在开头的地方有错误。这里我尝试这吧xml的文档声明给去掉了,居然没有报错。这里有些不理解为什么不能加? 我的方法:f_xml=test_xml.replace('<?xml version="1.0" encoding="gbk"?>','')
3. 然后再加载,就能获取到相应的节点了。

E. Python get返回xml解析问题

你这贴的代码格式都不调一下,看的好痛苦。。。。。

另:贴一份我早期写的一个解析xml转换为字典的代码,支持中文

细微部分,你自己调

importxml.etree.ElementTreeasET
importos
'''
将指定目录下的xml文件转换为字典dict
strXmlFileName:xml文件name
strElementPath:xml节点
dictSubElement:dict用于返回
eg.my_dict=xml2dict('xxx.xml','node',my_dict)
'''
defxml2dict(strXmlFileName,strElementPath,dictSubElement):
elementList=[]
dictSubElement.clear()
try:
eTree=ET.parse(os.getcwd()+strXmlFileName)
exceptException,errorinfo:
print"xml2dict:ET.parse(%s)generateexception,errorinfo:%s"%((os.getcwd()+strXmlFileName),errorinfo)
raiseerrorinfo

try:
elementList=eTree.findall(strElementPath)
exceptException,errorinfo:
print"xml2dict:eTree.findall(%s)generateexception,errorinfo:%s"%(strElementPath,errorinfo)
raiseerrorinfo

pathList=[]
forelementinelementList:
forsubelementinelement.getchildren():
#print"tag:%s,text:%s"%(subelement.tag,subelement.text.encode("utf-8"))
ifsubelement.textisnotNone:
ifsubelement.taginpathList:
dictSubElement[subelement.tag]=(os.getcwd()+subelement.text).encode('utf-8')
else:
dictSubElement[subelement.tag]=subelement.text.encode('utf-8')
else:
dictSubElement[subelement.tag]=""#将None赋值一串空字符串

F. python读取xml文件报错ValueError: multi-byte encodings are not supported

问题 在使用python对xml文件进行读取时,提示ValueError: multi-byte encodings are not supported

xml是用gb2312编码的。

很多贴子上说把xml的编码格式改为utf-8,就可以正常执行了。

但是这里有一个问题,xml原先的编码格式和encoding字段显示的编码格式都是gb2312,如果只改了encoding字段,之后再使用这个xml文件,就会按utf-8解析gb2312,会造成不可预知的后果。
第二个问题就是指改一个xml文件还好,但是有几百上千的时候,改这个就不方便了。
解决方案 用parseString函数
python提供了两种xml的输入方式,一种是文件,一种是字符串。我们可以先将xml文件读入内存,然后关闭文件。再将xml字符串中的gb2312用replace改为utf-8,然后用parseString解析,这样就不会报错。

注意事项 如果文件过大,有可能内存不够,所以适用于小的xml文件。注意要把不使用的文件给close掉,以免占用文件描述符。

G. 如何用python提取XML中的注释

from xml.etree import ElementTreestr_ = '' #文件中的xml字符串xml_obj = ElementTree.fromstring(str_)

然后通过对xml_obj进行操作,xml_obj本身也是一个xml节点。
xml_obj.getchildren() 获取根节点的子节点列表
xml_obj.findall(node_name) 搜索xml_obj节点下名为node_name的所有节点
xml_obj.tag 节点的标签
xml_obj.text 节点的文本信息 ,本例中可以获得K这个文本。
xml_obj.tail 节点尾部的文本信息,本例中获取Channel Regulator KCR1 Suppresses Heart Rhythm by Molating the Pacemaker Current I 就需要搜索到标签为sup的节点,然后取节点的tail文本获得。

H. 用python解析XML格式的字符串

你这样的数据还没有用正则来的简单
r'(?<=\<Result\>)(.+?)(?=\</Result\>)'

用XML会比较麻烦:
dom1 = minidom.parseString(xml)
result = dom1.getElementsByTagName("Result")
result = result[0].childNodes[0].nodeValue

I. python 解析xml 对xml字符串的长度有要求吗

没有,只对xml的格式有要求。

如果解决了您的问题请采纳!
如果未解决请继续追问!

热点内容
数据库access2003 发布:2024-05-19 02:49:39 浏览:619
碧蓝航线pc挂机脚本 发布:2024-05-19 02:30:03 浏览:588
脚本fir 发布:2024-05-19 02:28:57 浏览:260
阿里云独享服务器 发布:2024-05-19 02:23:54 浏览:253
织梦源码ga 发布:2024-05-19 02:23:20 浏览:571
java文件名后缀 发布:2024-05-19 02:14:39 浏览:956
快手点榜脚本 发布:2024-05-19 02:08:44 浏览:163
pythonforinkeys 发布:2024-05-19 01:55:44 浏览:793
电脑如何局域网共享文件夹 发布:2024-05-19 01:25:01 浏览:69
手机存储越大性能越好吗 发布:2024-05-19 01:14:28 浏览:177