栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从python中的xml文档中提取文本

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从python中的xml文档中提取文本

您可以简单地去除所有标签:

>>> import re>>> txt = """<bookstore>...     <book category="COOKING">...         <title lang="english">Everyday Italian</title>...         <author>Giada De Laurentiis</author>...         <year>2005</year>...         <price>300.00</price>...     </book>......     <book category="CHILDREN">...         <title lang="english">Harry Potter</title>...         <author>J K. Rowling </author>...         <year>2005</year>...         <price>625.00</price>...     </book>... </bookstore>""">>> exp = re.compile(r'<.*?>')>>> text_only = exp.sub('',txt).strip()>>> text_only'Everyday Italiann        Giada De Laurentiisn        2005n        300.00n  nn    n        Harry Pottern        J K. Rowling n        2005n        625.00'

但是,如果您只想在Linux中搜索文件中的某些文本,则可以使用

grep

burhan@sandbox:~$ grep "Harry Potter" file.xml        <title lang="english">Harry Potter</title>

如果要搜索文件,请使用

grep
上面的命令,或打开文件并在Python中搜索:

>>> import re>>> exp = re.compile(r'<.*?>')>>> with open('file.xml') as f:...     lines = ''.join(line for line in f.readlines())...     text_only = exp.sub('',lines).strip()...>>> if 'Harry Potter' in text_only:...    print 'It exists'... else:...    print 'It does not'...It exists


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/669881.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号