Здесь неполный ответ, который поможет вам с помощью numpy
пронумеровать теги. Я принял ту же структуру. Скажем, у нас есть
XML = """<GeneralQuestions>
<HeaderText>Pain Management Assessment</HeaderText>
<QuestionText>Pain assessment</QuestionText>
<QuestionAnswer>Yes</QuestionAnswer>
<HeaderText>Activities of Daily Living</HeaderText>
<QuestionText>Patient walks</QuestionText>
<QuestionAnswer>With Some Help</QuestionAnswer>
<Score>1</Score>
<HeaderText>Pain Management Assessment</HeaderText>
<QuestionText>Patient consents to having Pain Management Assessment screening completed.</QuestionText>
<QuestionAnswer>Patient accepts</QuestionAnswer>
<HeaderText>Activities of Daily Living</HeaderText>
<QuestionText>Patient gets dressed</QuestionText>
<QuestionAnswer>With Some Help</QuestionAnswer>
<Score>1</Score>
</GeneralQuestions>"""
И мы создаем дерево с
import xml.etree.ElementTree as ET
tree = ET.fromstring(XML)
Чем с помощью numpy
мы можем создать индекс с
import numpy as np
index_of_score = np.cumsum( [ e.tag == 'HeaderText' for e in tree.getchildren() ] )
Теперь с с помощью index_of_score
вы можете создать словарь с индексированными тегами и возможным значением
{ "{}_{}".format(a.tag,i) : a.text for i,a in zip(index_of_score, tree.getchildren() ) }
, которое даст вам
{'HeaderText_1': 'Pain Management Assessment',
'QuestionText_1': 'Pain assessment',
'QuestionAnswer_1': 'Yes',
'HeaderText_2': 'Activities of Daily Living',
'QuestionText_2': 'Patient walks',
'QuestionAnswer_2': 'With Some Help',
'Score_2': '1',
'HeaderText_3': 'Pain Management Assessment',
'QuestionText_3': 'Patient consents to having Pain Management Assessment screening completed.',
'QuestionAnswer_3': 'Patient accepts',
'HeaderText_4': 'Activities of Daily Living',
'QuestionText_4': 'Patient gets dressed',
'QuestionAnswer_4': 'With Some Help',
'Score_4': '1'}
В зависимости от желаемого результата вы можете выбрать ценности, которые вам нужны. Скажем, в приведенном выше словаре dict_output
, python есть хороший dict_output.get("Score_1", None)
, который даст вам либо значение, либо, в данном случае, None
, которое может помочь вам в обработке данных.