※ 공부하는 포스팅으로 틀린 것이나 맞지 않는 표현 있을 수 있습니다. 피드백받습니다!!
파이썬에서 word 파일 중 표를 handling 해야 하는 일이 생겨서 이용하게 되었다. 표를 다루면서 알게 된 것들을 정리한다.
사용 환경
- window10
- vscode
- jupyter notebook
버전
- python 3.10.2
- docx 0.2.4
install method
$ pip install python-docx
Word file example
word 파일의 표는 docx 라이브러리에서 table이라고 불리며 표 handling은 다음과 같이 크게 3개의 방법으로 다룰 수 있다. 코드는 나중에 코드 파트에서 table에서 cell값에 접근하는 것을 순차적으로 해보며 다루기로 한다.
table handling example
1. 표 읽기
2. 행 읽기
3. 열 읽기
start code
접근하고 싶은 cell은 다음과 같다.
위 셀을 읽기 위한 진행은 다음과 같다.
1. 표(table)를 읽기
from docx import Document
#파일 위치\\파일이름 할것
path = 'C:\code\\test_docx.docx'
document_test = Document(path)
#문서 내 전체표를 객체로 가져옴
table=document_test.tables
table
[<docx.table.Table at 0x16b5a9a5b10>]
결과 값을 보면 리스트 괄호에 table의 값이 들어가 있다.
[<docx.table.Table at 0x16b5a997eb0>, <docx.table.Table at 0x16b5a997ee0>]
표가 여러 개 일 경우 파이썬 list append처럼 뒤에 추가되는 형태로 구성이 이루어진다.
2. 행(row) 읽기
table[0].rows[0]
<docx.table._Row at 0x16b5aa2df00>
위의 코드는 table 0번째에 row 0 번째를 읽어오는 코드이다.
3. 셀(cell) 읽기
table[0].rows[0].cells[1]
<docx.table._Cell at 0x16b5a9a5c30>
위의 코드는 table 0번째에 row 0 번째에 cell 1번째를 읽어오는 코드이다.
여기서 text를 가져오기 위해 다음의 코드를 덧붙인다.
table[0].rows[0].cells[1].text
'\n4\n'
. text를 붙이게 되면 읽었던 cell의 text 값을 읽어 올 수 있게 된다.
여기까지 해서 word 파일을 파이썬의 docx 라이브러리를 이용하여 handling 하는 것을 알아보았다. 여러 개의 표를 읽고 원하는 cell에 접근하려면 약간의 for 문 코딩을 통해 값에 접근할 수 있을 것입니다. 더 자세한 사항은 reference를 참고하거나 구글링을 해보는 것을 추천합니다.
Reference
python-docx
Create and update Microsoft Word .docx files.
pypi.org
Table objects — python-docx 0.8.11 documentation
Table objects Table objects are constructed using the add_table() method on Document. class docx.table.Table(tbl, parent)[source] Proxy class for a WordprocessingML element. add_column(width)[source] Return a _Column object of width, newly added rightmost
python-docx.readthedocs.io
'python' 카테고리의 다른 글
[python] 파이썬 자습서 2. 파이썬 인터프리터 사용하기 (0) | 2022.06.17 |
---|---|
[python] 파이썬 자습서 1. 입맛 돋우기 (0) | 2022.06.15 |
[python] 지도 라이브러리 Folium 사용기 (0) | 2022.06.05 |
[python] shebang line (0) | 2022.05.17 |
[python] 파이썬 자습서 0. (1) | 2022.05.14 |