这是示例xml文档:
<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>
我想提取文本而不指定元素我该怎么做,因为我有10个这样的文档。我想这样,因为我的问题是用户输入了一些我不知道的单词,必须在各自文本部分的所有10个xml文档中进行搜索。要做到这一点,我应该知道文本的位置而不了解元素。还有一件事是所有这些文件都不同。
请帮助!!
答案 0 :(得分:1)
可以使用带有xpath查询的lxml库:
xml="""<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>
"""
from lxml import etree
root = etree.fromstring(xml).getroot()
root.xpath('/bookstore/book/*/text()')
# ['Everyday Italian', 'Giada De Laurentiis', '2005', '300.00', 'Harry Potter', 'J K. Rowling ', '2005', '625.00']
虽然你没有得到类别......
答案 1 :(得分:0)
你可以简单地删除任何标签:
>>> 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 Italian\n Giada De Laurentiis\n 2005\n 300.00\n
\n\n \n Harry Potter\n J K. Rowling \n 2005\n 6
25.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
答案 2 :(得分:0)
如果你想从python里面调用grep,请参阅讨论here,特别是this帖子。
如果你想搜索目录中的所有文件,你可以尝试使用glob模块:
import glob
import os
import re
p = re.compile('>.*<')
os.chdir("./")
for files in glob.glob("*.xml"):
file = open(files, "r")
line = file.read()
list = map(lambda x:x.lstrip('>').rstrip('<'), p.findall(line))
print list
print
此搜索遍历目录中的所有文件,打开每个文件并扩展与正则表达式匹配的文本。
输出:
['Everyday Italian', 'Giada De Laurentiis', '2005', '300.00', 'Harry Potter', 'J
K. Rowling ', '2005', '625.00']
编辑:更新了代码,仅从xml中提取文本元素。