Spaces:
Running
Running
| """ | |
| Extract text from old .doc (OLE2) file using olefile. | |
| Usage: python extract_doc.py <path_to_doc> | |
| """ | |
| 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('<H', char)[0] | |
| if 0x4E00 <= code <= 0x9FFF or 0x3000 <= code <= 0x303F or \ | |
| 0x0020 <= code <= 0x007E or 0xFF00 <= code <= 0xFFEF or \ | |
| code in (0x000D, 0x000A, 0x0009): | |
| text_parts.append(chr(code) if code < 0x10000 else '?') | |
| elif text_parts and text_parts[-1] != '\n': | |
| text_parts.append('\n') | |
| i += 2 | |
| text = ''.join(text_parts) | |
| # Clean up the text | |
| lines = [] | |
| for line in text.split('\n'): | |
| line = line.strip() | |
| if line and len(line) > 1: | |
| lines.append(line) | |
| print('\n'.join(lines)) | |
| ole.close() | |