파이썬3 노트

ElementTree로 xml파일 읽어오기 (2)

Jonchann 2019. 7. 8. 16:35

저번 글 => 2019/05/07 - [파이썬3 노트] - ElementTree로 xml파일 읽어오기 ①

저번 글에서 root를 찾고 root.find("이름")을 하면 각 요소에 for를 돌리지 않고도 찾아올 수 있다고 했다.

하지만 find는 가장 첫 요소만 갖고오기 때문에 for문과 섞어서 써야 한다는 말도 했다.

저번에 참고했던 SemEval데이터의 일부분을 적어놓고 시작하겠다.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Reviews>
    <Review rid="79">
        <sentences>
            <sentence id="79:0">
                <text>Being a PC user my whole life....</text>
            </sentence>
            <sentence id="79:1">
                <text>This computer is absolutely AMAZING!!!</text>
                <Opinions>
                    <Opinion category="LAPTOP#GENERAL" polarity="positive"/>
                </Opinions>

 

 

도큐멘트(저번 글에 링크 있음)를 더 읽고 findall과 iter을 발견했다.

findall은 현재 접근해 있는 요소 바로 아래 요소에만 접근할 수 있는 메소드라 한다.

find와 다르게 for loop으로 돌릴 수 있다.

import xml.etree.ElementTree as ET


tree = ET.parse("파일 path")
root = tree.getroot()
for review in root.findall("Review"):
    print(f"review.attrib => {review.attrib}")

출력 결과는 {'rid': '79'}이다

 

 

하지만 바로 내부(sentence)로 접근하고 싶다면 root.iter("sentence")를 사용하는 것이 더 효율적이다.

for loop를 덜 돌리기 때문이다.

for sentence in root.iter("sentence"):
    for content in sentence:
        if content.tag == "Opinons":
            for opinion in content:
                print(f"opinion.attrib => {opinion.attrib}")
        else:
            print(f"content.text => {content.text}")

출력 결과는 아래와 같다.

content.text => Being a PC user my whole life....
content.text => This computer is absolutely AMAZING!!!
opinion.attrib => opinion => {'category': 'LAPTOP#GENERAL', 'polarity': 'positive'}