""" Extract text from old .doc (OLE2) file using olefile. Usage: python extract_doc.py """ import sys, olefile, re, struct path = sys.argv[1] ole = olefile.OleFileIO(path) # Read the WordDocument stream doc_stream = ole.openstream('WordDocument').read() # Read the Table stream or 0Table for table_name in ['1Table', '0Table']: if ole.exists(table_name): table_stream = ole.openstream(table_name).read() break else: table_stream = None # Read Text pieces from the document # The .doc format stores text in Unicode (UTF-16LE) # Try to extract text by scanning for readable sequences print("=" * 60) print("文档内容提取") print("=" * 60) # Method 1: Extract UTF-16LE text text_parts = [] i = 0 while i < len(doc_stream) - 1: # Read 2 bytes as UTF-16LE char = doc_stream[i:i+2] code = struct.unpack(' 1: lines.append(line) print('\n'.join(lines)) ole.close()