Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 30 |
Tags
- 이미지읽어오기
- OS
- 이클립스프로젝트
- 데이터
- Python
- 이미지연산
- gitcommand
- 파이썬
- defaultbranch
- image
- powershell에러해결
- powershell에러
- 라이브러리
- 엑셀
- 프로그래밍
- 일치도
- 데이터분석
- 통계
- github
- 파이썬에러
- 머신러닝
- 반복문
- windowpowershell
- 이미지
- git
- 카파
- 깃에러
- 코딩
- 깃허브
- 코드
Archives
- Today
- Total
나중에 내가 보려고 만든 블로그
[Python] ElementTree 사용하여 xml 파싱, 수정하기 본문
https://docs.python.org/ko/3/library/xml.etree.elementtree.html
xml.etree.ElementTree — ElementTree XML API — Python 3.10.2 문서
소스 코드: Lib/xml/etree/ElementTree.py xml.etree.ElementTree 모듈은 XML 데이터를 구문 분석하고 만들기 위한 단순하고 효율적인 API를 구현합니다. 버전 3.3에서 변경: 이 모듈은 가능할 때마다 빠른 구현을
docs.python.org
해당 문서 참고하여 기본적인 기능 사용해보았다.
xml 파일을 수정하고 난 뒤 write 할때 xml 파일이 indent 없이 한줄로 쭉 이어서 수정되어있다면
본문 제일 아래 코드블럭에 있는 indent 함수를 사용하면 된다.
원본 xml은 이런 형태인데 if문 사용하여 특정 조건에 부합하면 xml이 수정되도록 해보았음.

아래는neighbor 엘리먼트에서 attribute direction이 "E"인 경우 "Non"으로 수정한 결과임.

위와 같은 xml이 여러개 있는 경우 아래처럼 하나의 경로에 넣고 반복문으로 수정할 수 있다,
아래는 indentation, write까지해서 다시 수정한 xml을 저장한 코드이다.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
import os
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element, SubElement, ElementTree, dump
import pandas as pd
file_path = "/data/"
file_list = os.listdir(file_path)
pd.set_option('display.max_rows', None)
## indentation
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
for fl_nm in file_list :
tree = ET.parse( file_path + fl_nm )
root = tree.getroot()
n_roof = 1
for neighbor in root.iter("neighbor") :
if(neighbor.attrib["direction"] == "E") :
neighbor.attrib["direction"] = "Non"
indent(root)
tree = ElementTree(root)
tree.write( file_path + fl_nm )
print( "#" + fl_nm + "done")
|
cs |
반복적인 일을 최대한 효율적으로 하고자 xml 파싱을 시작한거라서 자주 사용했다.
'Python' 카테고리의 다른 글
| [Python] opencv 바이너리 이미지 비트연산 (0) | 2022.06.23 |
|---|---|
| [Python] 이미지 읽어오기, RGB 값 추출, RGB 평균 구하기 (0) | 2022.05.16 |
| [Python] openslide 라이브러리 기능, 이미지 metadata 추출 (0) | 2022.03.07 |
| [Python] 엑셀리스트로 파일명 일괄 변경, xlrd 라이브러리 (0) | 2022.01.03 |
| [Python] tqdm : 반복문에서 진행률 표시 (0) | 2021.08.06 |