Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีอ่านไฟล์ Microsoft Word ด้วย Python

บทนำ

Python-docx อ่านเนื้อหาใน .docx ไม่ได้ดี ต้องอ่าน XML ดิบด้วยตนเอง โดย .docx เป็นไฟล์ zip ที่มี word/document.xml ภายใน

ขั้นตอน

  1. นำเข้า: from zipfile import ZipFile, from urllib.request import urlopen, from io import BytesIO
  2. ดาวน์โหลดไฟล์ .docx เป็น binary, แปลงเป็น BytesIO
  3. เปิดด้วย ZipFile อ่าน 'word/document.xml'
  4. decode UTF-8 ได้ XML content

ตัวอย่างโค้ด

from zipfile import ZipFile
from urllib.request import urlopen
from io import BytesIO

file_url = 'https://file-examples-com.github.io/uploads/2017/02/file-sample_100kB.docx'
wordDocx = urlopen(file_url).read()
wordDocx = BytesIO(wordDocx)
document = ZipFile(wordDocx)
xml_content = document.read('word/document.xml')
print(xml_content.decode('utf-8'))

XML ที่ได้จะมี namespace w: และข้อความอยู่ในแท็ก <w:t> สามารถ parse ด้วย xml.etree.ElementTree หรือ regex เพื่อดึงข้อความ純文本