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

发布于 2021-01-29 14:59:12

这是示例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
被浏览
105
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

    >>> 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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看