Python 解析一个 xml 文件传递​​结果到数组

Python parse an xml file pass result to array

我正在尝试解析一个我已经完成的 xml 文件,并将结果传递到一个稍后将使用的数组中。 xml 在我挑选 3 个元素(频道、开始和标题)的地方被打开读取和解析。如下代码所示,开始是日期和时间。我能够拆分日期和时间并存储在日期中。当代码循环遍历每个 xml 条目时,我想选择频道、开始和标题并将其存储到多维数组中。我在 Brightscript 中完成了此操作,但无法理解 Python 的数组或列表结构。一旦我拥有数组或列表中的所有条目,我将需要解析该数组以提取所有具有相同日期的标题和日期。有人可以指导我完成这个吗?

xmldoc=minidom.parse (xmldoc)
programmes= xmldoc.getElementsByTagName("programme")
def getNodeText(node):
    nodelist = node.childNodes
    result = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            result.append(node.data)
    return ''.join(result)

title = xmldoc.getElementsByTagName("title")[0]
#print("Node Name : %s" % title.nodeName)
#print("Node Value : %s \n" % getNodeText(title))
programmes = xmldoc.getElementsByTagName("programme")

for programme in programmes:
    cid = programme.getAttribute("channel")
    starts=programme.getAttribute("start")
    cutdate=starts[0:15]
    year= int(cutdate[0:4])
    month= int(cutdate[5:6])
    day= int(cutdate[7:8])
    hour= int(cutdate[9:10])
    minute= int(cutdate[11:12])
    sec= int(cutdate[13:14])
    date=datetime(year, month, day,hour, minute, sec)
    title = programme.getElementsByTagName("title")[0]
    print("id:%s, title:%s, starts:%s" %
          (cid, getNodeText(title), starts))
    print (date)

Python 通常将数组称为 lists,看起来你想要的是一个列表列表(有一个 array 模块和整个 numpy带有自己的数组的扩展,但它看起来不像你想要的:-)。

因此将所需列表设为空:

results = []

在你现在打印东西的地方,将它们附加到列表中:

results.append([cid, getNodeText(title), date])

(或者其他什么——你的缩进太杂乱了,会导致 Python 中出现大量语法错误,让我对你到底想要什么感到困惑:-)。

现在开始

I will need to parse that array pulling out all titles and dates with the same date

只需按日期对结果进行排序:

import operator

results.sort(key=operator.itemgetter(2))

然后分组:

import itertools

for date, items in itertools.groupby(results, operator.itemgetter(2)):
    print(date,[it[1] for it in items])

或您要对此分组执行的任何其他操作。

您可以通过多种方式改进此样式,但这似乎确实为您提供了您所要求的关键功能。