Python 스크립팅을 사용하여 XML에서 다른 요소의 텍스트 또는 속성을 기반으로 요소의 텍스트 가져 오기

Enigmaderockz

이름, 나이, 성별의 복잡성과 같은 특정 세부 사항에 대해 학생의 이름을 얻고 싶습니다. "maths"또는 "married"라는 텍스트에 대해 rick Grimes라는 이름을 가져와야합니다. "여성"이라는 텍스트의 경우 Daryl이라는 이름을 가져야합니다. "low"속성에 대해 Maggie를 가져와야합니다. 많은 문서를 읽었지만 XML python에서 어떤 요소로도 이동하고 다른 요소 텍스트 값이나 속성을 기반으로 해당 텍스트를 가져올 수있는 함수를 찾지 못했습니다. 누군가 도울 수 있습니까?

<students>
 <student>
   <name>Rick Grimes</name>
   <age>35</age>
   <subject complexity = "Medium">Maths</subject>
   <gender>Male</gender>
   <personal details>
     <status>married</status>
   </personal details>
 </student>

 <student>
   <name>Daryl Dixon </name>
   <age>33</age>
   <subject complexity = "Small">Science</subject>
   <gender>Female</gender>
   <personal details>
     <status>single</status>
   </personal details>
 </student>

 <student>
   <name>Maggie</name>
   <age>36</age>
   <subject complexity = "low">Arts</subject>
   <gender>Others</gender>
 </student>
</students>
새미 웨미

lxml에 빌드 된 parsel 을 사용 하여 데이터를 그룹화 할 수 있습니다.

from parsel import Selector
data = """[your html above"""]
selector = Selector(data)

#create a list of first level elements in ```student``` section
keys = ['name','age','subject','gender']
coll = []

#iteration here
for entry in selector.xpath(".//student"):
    #get the dictionary pairing for element and text for each key in keys
    d = {ent : entry.xpath(f"./{ent}/text()").get() for ent in keys}

    #get data for the attribute complexity and the sub element status
    others = {'complexity' : entry.xpath(f"./subject/@complexity").get(),
              'status' : entry.xpath(".//status/text()").get()
             }

    #add to main dictionary
    d.update(others)

    #collect into a list
    coll.append(d)

print(coll)


[{'name': 'Rick Grimes',
  'age': '35',
  'subject': 'Maths',
  'gender': 'Male',
  'complexity': 'Medium',
  'status': 'married'},
 {'name': 'Daryl Dixon ',
  'age': '33',
  'subject': 'Science',
  'gender': 'Female',
  'complexity': 'Small',
  'status': 'single'},
 {'name': 'Maggie',
  'age': '36',
  'subject': 'Arts',
  'gender': 'Others',
  'complexity': 'low',
  'status': None}]

이제 세부 사항을 기준으로 필터링 할 수 있습니다. 예를 들어 제목이 수학이면 이름을 찾습니다.

for entry in coll:
    if entry['subject'] == "Maths":
        print(entry['name'])

Rick Grimes

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관