-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathfix_anchor.py
More file actions
executable file
·290 lines (226 loc) · 7.85 KB
/
fix_anchor.py
File metadata and controls
executable file
·290 lines (226 loc) · 7.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#!/usr/bin/env python
# -*- coding: utf-8 -*-
########################################################################
# fix_anchor.py: Normalize reference anchor placement before punctuation
#
# Description:
# This script normalizes HTML reference anchors so that anchors linked to
# "#ref<number>" appear before Japanese full stops.
#
# It rewrites patterns such as:
# 。<a href="#ref1">[1]</a>
# 。 <a href="#ref1">[1]</a>
# 。<a href="#ref1">[1]</a><a href="#ref2">[2]</a>
# 。<a href="#ref1">[1]</a>
#
# into:
# <a href="#ref1">[1]</a>。
# <a href="#ref1">[1]</a><a href="#ref2">[2]</a>。
# <a href="#ref1">[1]</a>。
#
# The script updates the input file in place by default, or writes to a
# separate output file when OUTPUT is specified.
#
# Author: id774 (More info: http://id774.net)
# Source Code: https://github.com/id774/scripts
# License: The GPL version 3, or LGPL version 3 (Dual License).
# Contact: idnanashi@gmail.com
#
# Requirements:
# - Python Version: 3.1 or later
# - Standard library only
#
# Usage:
# fix_anchor.py INPUT [OUTPUT]
# fix_anchor.py -h | --help
# fix_anchor.py -v | --version
#
# Options:
# - INPUT
# Input HTML file.
# - OUTPUT
# Output HTML file. If omitted, INPUT is updated in place.
# - -h, --help
# Display this help and exit.
# - -v, --version
# Display version information and exit.
#
# Version History:
# v1.0 2026-03-26
# Initial release.
#
########################################################################
import os
import re
import sys
# Match a reference anchor whose href is "#ref<number>".
REF = r'<a\b[^>]*\bhref\s*=\s*["\']#ref\d+["\'][^>]*>\[\d+\]</a>'
# Match consecutive reference anchors.
# Preserve whitespace between anchors as part of the matched block.
REF_RUN = r'%s(?:[ \t\r\n]*%s)*' % (REF, REF)
# Match literal Japanese full stop followed by optional whitespace and refs.
PATTERN = re.compile(
r'(?P<punct>。)(?P<gap>[ \t\r\n]*)(?P<refs>%s)' % REF_RUN
)
# Match HTML entity form of Japanese full stop followed by refs.
ENTITY_PATTERN = re.compile(
r'(?P<punct>。)(?P<gap>[ \t\r\n]*)(?P<refs>%s)' % REF_RUN
)
def usage():
"""Display the script header as usage information and exit."""
script_path = os.path.abspath(__file__)
in_header = False
try:
with open(script_path, "r", encoding="utf-8") as f:
for line in f:
if line.strip().startswith("#" * 10):
if not in_header:
in_header = True
continue
break
if in_header and line.startswith("#"):
if line.startswith("# "):
print(line[2:], end="")
else:
print(line[1:], end="")
except Exception as e:
print("Error reading usage information: %s" % str(e), file=sys.stderr)
sys.exit(2)
sys.exit(0)
def get_script_version():
"""Extract script version from header."""
script_path = os.path.abspath(__file__)
found_history = False
try:
with open(script_path, 'r', encoding='utf-8') as handle:
for line in handle:
if "Version History" in line:
found_history = True
elif found_history and line.strip().startswith("# v"):
return line.strip().split()[1]
except Exception:
return "unknown"
return "unknown"
def show_version():
"""Display version information."""
version = get_script_version()
print("fix_anchor.py %s" % version)
return 0
def validate_input_file(path):
"""Validate the input file path."""
if not os.path.exists(path):
print("[ERROR] Input file does not exist: %s" % path, file=sys.stderr)
return 1
if not os.path.isfile(path):
print("[ERROR] Input path is not a file: %s" % path, file=sys.stderr)
return 1
return 0
def validate_input_content(path):
"""Validate that the input file is a supported text file for this script."""
try:
with open(path, "rb") as handle:
raw = handle.read(4096)
except Exception as exc:
print("[ERROR] Failed to read input file for validation: %s (%s)" %
(path, str(exc)), file=sys.stderr)
return 1
if b"\x00" in raw:
print("[ERROR] Binary file is not supported: %s" % path, file=sys.stderr)
return 1
try:
with open(path, "r", encoding="utf-8") as handle:
text = handle.read()
except UnicodeDecodeError:
print("[ERROR] Input file is not valid UTF-8 text: %s" % path,
file=sys.stderr)
return 1
except Exception as exc:
print("[ERROR] Failed to decode input file: %s (%s)" %
(path, str(exc)), file=sys.stderr)
return 1
if "<a" not in text or "#ref" not in text:
print("[ERROR] Input file does not look like target HTML text: %s" % path,
file=sys.stderr)
return 1
return 0
def fix_with_pattern(text, pattern):
"""Apply one normalization pattern and return updated text and count."""
counter = [0]
def repl(match):
"""Move the reference block before the punctuation."""
counter[0] += 1
return "%s%s" % (match.group("refs"), match.group("punct"))
updated = pattern.sub(repl, text)
return updated, counter[0]
def fix(text):
"""Normalize reference anchor placement around punctuation."""
updated, count1 = fix_with_pattern(text, PATTERN)
updated, count2 = fix_with_pattern(updated, ENTITY_PATTERN)
return updated, (count1 + count2)
def read_text_file(path):
"""Read a UTF-8 text file."""
try:
with open(path, "r", encoding="utf-8") as handle:
return handle.read(), 0
except Exception as exc:
print("[ERROR] Failed to read file: %s (%s)" % (path, str(exc)),
file=sys.stderr)
return None, 1
def write_text_file(path, text):
"""Write a UTF-8 text file."""
try:
with open(path, "w", encoding="utf-8", newline="") as handle:
handle.write(text)
except Exception as exc:
print("[ERROR] Failed to write file: %s (%s)" % (path, str(exc)),
file=sys.stderr)
return 1
return 0
def parse_arguments(argv):
"""Parse command-line arguments."""
if not argv:
print("[ERROR] Missing input file", file=sys.stderr)
return None, None, 1
if len(argv) == 1:
arg = argv[0]
if arg in ("-h", "--help"):
return "help", None, 0
if arg in ("-v", "--version"):
return "version", None, 0
return arg, arg, 0
if len(argv) == 2:
if argv[0] in ("-h", "--help", "-v", "--version"):
print("[ERROR] Option does not accept an extra argument: %s" % argv[0],
file=sys.stderr)
return None, None, 1
return argv[0], argv[1], 0
print("[ERROR] Invalid arguments", file=sys.stderr)
return None, None, 1
def main():
"""Run the main processing flow."""
input_path, output_path, status = parse_arguments(sys.argv[1:])
if status != 0:
usage()
return 1
if input_path == "help":
return usage()
if input_path == "version":
return show_version()
status = validate_input_file(input_path)
if status != 0:
return status
status = validate_input_content(input_path)
if status != 0:
return status
text, status = read_text_file(input_path)
if status != 0:
return status
updated_text, count = fix(text)
status = write_text_file(output_path, updated_text)
if status != 0:
return status
print("[INFO] Updated: %d" % count)
print("[INFO] Written to: %s" % output_path)
return 0
if __name__ == "__main__":
sys.exit(main())