MIF_E31231430/read_docx.py

55 lines
2.2 KiB
Python

import zipfile
import xml.etree.ElementTree as ET
import os
def get_docx_text(path):
print(f"--- CONTENT OF {os.path.basename(path)} ---")
try:
import docx
doc = docx.Document(path)
fullText = []
for para in doc.paragraphs:
fullText.append(para.text)
for table in doc.tables:
for row in table.rows:
row_text = [cell.text.strip().replace('\n', ' ') for cell in row.cells]
# remove consecutive duplicates from cell merging
cleaned_row = []
for t in row_text:
if not cleaned_row or cleaned_row[-1] != t:
cleaned_row.append(t)
fullText.append(" | ".join(cleaned_row))
return '\n'.join(fullText)
except ImportError:
# Fallback to direct xml parsing
try:
with zipfile.ZipFile(path) as docx_zip:
xml_content = docx_zip.read('word/document.xml')
root = ET.fromstring(xml_content)
# Simple extraction of text elements
# docx namespaces
namespaces = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
# Let's iterate over paragraphs and tables in order
texts = []
for elem in root.iter():
if elem.tag.endswith('t'):
if elem.text:
texts.append(elem.text)
elif elem.tag.endswith('cr') or elem.tag.endswith('br') or elem.tag.endswith('p'):
texts.append('\n')
elif elem.tag.endswith('tab'):
texts.append('\t')
return "".join(texts)
except Exception as e:
return f"Error: {e}"
if __name__ == "__main__":
for filename in ["Jenis penggunaan setelah wawancara pada pakar.docx", "Jenis Penggunaan Pada Pakar Owner Jember Kamera Mangli.docx"]:
if os.path.exists(filename):
print(get_docx_text(filename))
print("\n" + "="*50 + "\n")
else:
print(f"File {filename} not found.")