dsh-docx-format 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,143 @@
1
+ #!/usr/bin/env python3
2
+ """Docx 正文抽取器(纯标准库,不依赖 python-docx、不联网)。
3
+
4
+ 用法:
5
+ python docx_read.py <file.docx> [--offset 0] [--max-chars 12000] [--json]
6
+
7
+ 输出 JSON(--json):
8
+ {"ok": true, "path": ..., "total_chars": N, "offset": 0, "next_offset": N,
9
+ "text": "...", "paragraphs": N, "tables": N, "truncated": false, "notes": [...]}
10
+ """
11
+
12
+ import argparse
13
+ import json
14
+ import sys
15
+ import zipfile
16
+ from xml.etree import ElementTree as ET
17
+
18
+ W = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
19
+
20
+
21
+ def q(tag):
22
+ return W + tag
23
+
24
+
25
+ def para_text(p):
26
+ parts = []
27
+ for node in p.iter():
28
+ tag = node.tag
29
+ if tag == q('t'):
30
+ if node.text:
31
+ parts.append(node.text)
32
+ elif tag == q('tab'):
33
+ parts.append('\t')
34
+ elif tag in (q('br'), q('cr')):
35
+ parts.append('\n')
36
+ return ''.join(parts).strip()
37
+
38
+
39
+ def table_text(tbl):
40
+ rows = []
41
+ for tr in tbl.findall(q('tr')):
42
+ cells = []
43
+ for tc in tr.findall(q('tc')):
44
+ inner = [para_text(p) for p in tc.iter(q('p'))]
45
+ cells.append(' '.join(x for x in inner if x).strip())
46
+ if any(cells):
47
+ rows.append(' | '.join(cells))
48
+ return rows
49
+
50
+
51
+ def extract(path):
52
+ notes = []
53
+ with zipfile.ZipFile(path) as zf:
54
+ names = zf.namelist()
55
+ if 'word/document.xml' not in names:
56
+ return None, notes + ['zip 内没有 word/document.xml(可能是 .doc 或损坏文件)']
57
+ raw = zf.read('word/document.xml')
58
+ has_media = any(n.startswith('word/media/') for n in names)
59
+ has_footnote = 'word/footnotes.xml' in names
60
+ if has_media:
61
+ notes.append('文档含图片(word/media/),本抽取只取文字')
62
+ if has_footnote:
63
+ notes.append('文档含脚注,本抽取不含脚注文字')
64
+ try:
65
+ root = ET.fromstring(raw)
66
+ except ET.ParseError as exc:
67
+ return None, notes + ['document.xml 解析失败: %s' % exc]
68
+
69
+ body = root.find(q('body'))
70
+ if body is None:
71
+ return None, notes + ['document.xml 没有 w:body']
72
+
73
+ blocks = []
74
+ paragraphs = 0
75
+ tables = 0
76
+ for child in list(body):
77
+ tag = child.tag
78
+ if tag == q('p'):
79
+ text = para_text(child)
80
+ if text:
81
+ blocks.append(text)
82
+ paragraphs += 1
83
+ elif tag == q('tbl'):
84
+ rows = table_text(child)
85
+ if rows:
86
+ blocks.append('\n'.join('[表] ' + r for r in rows))
87
+ tables += 1
88
+ elif tag == q('sdt'):
89
+ for p in child.iter(q('p')):
90
+ text = para_text(p)
91
+ if text:
92
+ blocks.append(text)
93
+ paragraphs += 1
94
+
95
+ text = '\n'.join(blocks)
96
+ stats = {'paragraphs': paragraphs, 'tables': tables, 'chars': len(text)}
97
+ return (text, stats), notes
98
+
99
+
100
+ def main(argv=None):
101
+ ap = argparse.ArgumentParser()
102
+ ap.add_argument('path')
103
+ ap.add_argument('--offset', type=int, default=0)
104
+ ap.add_argument('--max-chars', type=int, default=12000)
105
+ ap.add_argument('--json', action='store_true')
106
+ args = ap.parse_args(argv)
107
+
108
+ try:
109
+ result, notes = extract(args.path)
110
+ except FileNotFoundError:
111
+ result, notes = None, ['文件不存在']
112
+ except zipfile.BadZipFile:
113
+ result, notes = None, ['不是有效的 docx(zip)文件']
114
+ except OSError as exc:
115
+ result, notes = None, ['读取失败: %s' % exc]
116
+
117
+ if result is None:
118
+ payload = {'ok': False, 'path': args.path, 'error': notes[0] if notes else '未知错误', 'notes': notes}
119
+ print(json.dumps(payload, ensure_ascii=False))
120
+ return 1
121
+
122
+ text, stats = result
123
+ offset = max(0, min(args.offset, len(text)))
124
+ chunk = text[offset:offset + max(200, args.max_chars)]
125
+ next_offset = offset + len(chunk)
126
+ payload = {
127
+ 'ok': True,
128
+ 'path': args.path,
129
+ 'total_chars': len(text),
130
+ 'paragraphs': stats['paragraphs'],
131
+ 'tables': stats['tables'],
132
+ 'offset': offset,
133
+ 'next_offset': next_offset if next_offset < len(text) else None,
134
+ 'truncated': next_offset < len(text),
135
+ 'text': chunk,
136
+ 'notes': notes,
137
+ }
138
+ print(json.dumps(payload, ensure_ascii=False))
139
+ return 0
140
+
141
+
142
+ if __name__ == '__main__':
143
+ sys.exit(main())