【问题标题】:extract text from xml documents in python从python中的xml文档中提取文本
【发布时间】:2012-07-02 00:51:52
【问题描述】:

这是示例 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 文档中进行搜索。为此,我应该在不知道元素的情况下知道文本的位置。还有一件事是所有这些文件都不同。

请帮忙!!

【问题讨论】:

    标签: python linux xml-parsing ubuntu-10.04


    【解决方案1】:

    你可以简单地去掉任何标签:

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

    【讨论】:

    • 有没有办法在另一个文件中使用 grep 虽然我知道它是一个要写在终端上的命令。只是大致了解
    • 嘿,它不起作用,因为您提供的示例是 xml string 。如果我需要在 xml 文件中执行此操作,因为我必须从中提取它的 xml 文件而不是从 xml 字符串中提取?
    • @POOJAGUPTA 不,这会在名为“file.xml”的文件中查找“Harry Potter”... XML 字符串是 grep 的输出...
    • @POOJAGUPTA,如果你想解析所有的 xml 文件或者你想从 python 中调用 grep,请查看我的答案。
    • @Jon: 我不想要 grep 的输出。你不是在 fromstring() 中发送参数“xml”吗?如果我没记错的话,您正在解析 xml 文档的部分?请解释一下,看看我是 xml 解析的新手,所以请告诉我如果我在某个地方错了。
    【解决方案2】:

    如果您想从 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 中提取文本元素。

    【讨论】:

      【解决方案3】:

      可以使用带有 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']
      

      虽然你没有得到类别....

      【讨论】:

      • 如果我需要在 xml 文档中执行此解析方法怎么办,因为您给出的答案是使用 xml 字符串。请回复。
      • 好的...我的回复是你的评论没有什么意义?
      • 您的 输入 是 XML。因此,出于演示目的,将复制/粘贴为字符串是有意义的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多