我有一些具有以下结构的XML:
<root>
<parent-1>
<text>blah-1</text>
<properties>
<property type="R" id="0005">text-value-A</property>
<property type="W" id="0003">text-value-B</property>
<property type="H" id="0002">text-value-C</property>
<property type="W" id="0008">text-value-D</property>
</properties>
</parent-1>
<parent-2>
<text>blah-2</text>
<properties>
<property type="W" id="0004">text-value-A</property>
<property type="H" id="0087">text-value-B</property>
</properties>
</parent-2>
<parent-3>
<text>blah-3</text>
<properties>
<property type="H" id="0087">text-value-C</property>
<property type="R" id="0008">text-value-A</property>
</properties>
</parent-3>
<parent-4>
<text>blah-4</text>
<properties>
<property type="H" id="0019">text-value-C</property>
<property type="R" id="0060">text-value-A</property>
</properties>
</parent-4>
</root>目前,我正在解析text-value-并使用一些字符串!连接它们,但是对于在属性级别上最后出现的text-value-X,我需要分配一些其他的字符串&,并输出类似于:text-value-A!text-value-B!text-value-C!text-value-D&text-value-A!text-value-B&text-value-C!text-value-A的内容。
由于<property中的属性不能特定于标记/具有随机值,所以类似于if(item.text == 'text-value-A') #get text-value-A of parent-3的内容将无法工作。
我不保留重复的text-value-s (在本例中不需要parent-4,因为parent-3的text-value-是相同的),我希望保持顺序,所以对于enumerate,我要做以下工作:
alist = []
for item in root.findall('parent/properties/property'):
alist.append(item.text)
self.alist = '!'.join([a for b,a in enumerate(alist) if a not in alist[:b]]考虑到上面所期望的输出,我想知道我是否需要一个不同的方法来解决这个问题,或者这样的概念会在某种程度上起作用:
alist = []
for item in root.findall('parent/properties/property'):
alist.append(item.text)
for element in alist:
if element in alist[-1]:
self.alist = '&'.join([a for b,a in enumerate(alist) if a not in alist[:b]]
if not element in alist[-1]:
self.alist = '!'.join([a for b,a in enumerate(alist) if a not in alist[:b]]谢谢
发布于 2018-01-10 22:55:10
这可能是你想要的。
property_texts将包含每个文本的列表。any谓词用于测试当前属性的文本集以前是否见过。如果没有,则将这些文本作为列表添加到集合中。(使用set逻辑以避免丢失不同顺序的重复集非常重要。)from xml.etree import ElementTree
tree = ElementTree.parse('bt123.xml')
property_text_lists = []
for properties in tree.findall('.//properties'):
property_texts = [p.text for p in properties]
if any([set(property_texts)==set(ptl) for ptl in property_text_lists]):
break
property_text_lists.append(property_texts)
print ('&'.join(['!'.join(property_text_lists[i]) for i in range(len(property_text_lists))]))它确实产生了这个输出。
text-value-A!text-value-B!text-value-C!text-value-D&text-value-A!text-value-B&text-value-C!text-value-Ahttps://stackoverflow.com/questions/48171974
复制相似问题