簡體   English   中英

如何使用Python的xml.dom.minidom從XML文件獲取字符串列表?

[英]How to obtain a list of strings from an XML file using Python's xml.dom.minidom?

全部-

我正在嘗試使用解析以下非常簡單的XML文檔結構

from xml.dom.minidom import parse

XML如下所示:

<?xml version="1.0" encoding="utf-8"?>
    <list>
       <file name="..." url="...">
       <words>
           word_1
           word_2
           ...

我遇到的問題是XML包含一個我想作為字符串列表訪問的單詞列表...而我似乎根本無法正確理解它。 到目前為止,這是我所擁有的代碼:

import sys
from xml.dom.minidom import parse

for file in sys.argv[1:]:

    dom = parse( file )

    title = dom.getElementsByTagName( 'job_ad' )[0].getAttribute( 'title' )
    # This works 

    words = dom.getElementsByTagName( 'unigrams' )[0].childNodes[0]

    # This is NOT a list of strings ... 

我想遍歷此代碼中的數據結構“字”。 我知道還有很多功能更強大的XML模塊可用...但是現在,我想用所示的模塊解決這個問題。

任何幫助,將不勝感激。

在此先感謝您,並誠摯的問候-

我假設單詞在words節點下以純文本形式列出,在這種情況下,您只需要從words節點獲取文本並將其拆分即可,例如

s="""<?xml version="1.0" encoding="utf-8"?>
    <list>
       <file name="..." url="...">
       <words>
           word_1
           word_2
        </words>
       </file>
    </list>"""

import sys
from xml.dom.minidom import parseString

dom = parseString(s)
words_text = dom.getElementsByTagName('words')[0].firstChild.nodeValue
words = words_text.split()
print words

輸出:

[u'word_1', u'word_2']

如果您未嫁給“ xml.dom.minidom”,則可能要簽出lxml(http://lxml.de/)

該代碼將是:

import lxml.etree
doc = lxml.etree.parse( open(file) )
words = doc.findtext('words')

WHOOPS-我現在看到張貼者特別要求使用'xml.dom.minidom'作為答案。 抱歉,我們使用lxml。 您可以忽略。

似乎在您的XML文檔中,多個word_X單詞被分組在一個xml元素內。 由於它們不是不同的XML元素,因此您不能像這樣查詢。 相反,您可以使用正則表達式來解析單個元素字符串
例如:假設您有wordListAsSingleString包含(如果可以查詢的話):

       word_1
       word_2

re.split('\\s+', wordListAsSingleString)將為您提供單詞列表。

如果希望單詞為字符串,請在末尾添加.data:

words = dom.getElementsByTagName( 'unigrams' )[0].childNodes[0].data

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM