我想包装for循环的功能,所以它会更直观地使用它。在我的情况,我要解析的XML文件是这样的:在python中循环包装
<instance id="line-n.w8_047:15696:">
<answer instance="line-n.w8_047:15696:" senseid="product" />
<context> context1 </context>
</instance>
<instance id="line-n.w8_088:12441:">
<answer instance="line-n.w8_088:12441:" senseid="product" />
<context> another context</context>
</instance>
我写了一个类Instance
这样的:
class Instance:
def __init__(self, id, answer, context):
self.id = id
self.answer = answer
self.context = context
我写了下面的函数来列举实例:
import xml.etree.ElementTree as ET
def enum_instances(file_path, action):
for instance_xml in ET.parse(file_path).getroot().find('lexelt'):
action(Instance(
instance_xml.attrib['id'],
instance_xml.find('answer').attrib['senseid'],
instance_xml.find('context').text)
)
action
参数是一个回调,用Instance
做一些动作,像这样:
enum_instances('/path/to/xml', lambda instance: print(instance.context))
,但它看起来有点奇怪,我想它更直观,就像这样:
for instance in enum_instances(file_path):
print(instance.context)
什么是实现“迭代”功能的最佳方法是什么? 感谢
那么为什么不这样做只是你想要什么呢?不要调用动作......而是......“yield”实例... –
顺便说一句,该XML文件不是XML。必须有一个根。 –
@ polkovnikov.ph你说得对,我的XML有一个根和一个凌乱的结构,但我只提出了相关部分的问题 –