read_docx.py 922 B

123456789101112131415161718192021222324
  1. import zipfile
  2. import xml.etree.ElementTree as ET
  3. def get_docx_text(path):
  4. try:
  5. doc = zipfile.ZipFile(path)
  6. xml_content = doc.read('word/document.xml')
  7. root = ET.fromstring(xml_content)
  8. # Word XML namespaces
  9. ns = {'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'}
  10. paragraphs = []
  11. for paragraph in root.iter('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}p'):
  12. texts = [node.text for node in paragraph.iter('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}t') if node.text]
  13. if texts:
  14. paragraphs.append("".join(texts))
  15. return "\n".join(paragraphs)
  16. except Exception as e:
  17. return f"Error reading {path}: {e}"
  18. if __name__ == "__main__":
  19. text = get_docx_text(r"c:\Users\lanfr144\Documents\DOPRO1\Antigravity\todo.docx")
  20. print(text)