forked from standardebooks/tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
british2american
executable file
·67 lines (54 loc) · 2.39 KB
/
british2american
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
#!/usr/bin/env python3
import argparse
import os
import fnmatch
import regex
IGNORED_FILES = ["colophon.xhtml", "titlepage.xhtml", "imprint.xhtml", "uncopyright.xhtml", "halftitle.xhtml", "toc.xhtml", "loi.xhtml"]
def main():
parser = argparse.ArgumentParser(description="Try to convert British quote style to American quote style. Quotes must already be \"typogrified\"--i.e. curly. This script isn't perfect; proofreading is required, especially near closing quotes near to em-dashes.")
parser.add_argument("-v", "--verbose", action="store_true", help="increase output verbosity")
parser.add_argument("targets", metavar="TARGET", nargs="+", help="an XHTML file, or a directory containing XHTML files")
args = parser.parse_args()
for target in args.targets:
target = os.path.abspath(target)
if args.verbose:
print("Processing {} ...".format(target), end="", flush=True)
target_filenames = set()
if os.path.isdir(target):
for root, _, filenames in os.walk(target):
for filename in fnmatch.filter(filenames, "*.xhtml"):
if filename not in IGNORED_FILES:
target_filenames.add(os.path.join(root, filename))
else:
target_filenames.add(target)
for filename in target_filenames:
with open(filename, "r+", encoding="utf-8") as file:
xhtml = file.read()
new_xhtml = xhtml
new_xhtml = british_to_american(new_xhtml)
if new_xhtml != xhtml:
file.seek(0)
file.write(new_xhtml)
file.truncate()
if args.verbose:
print(" OK")
def british_to_american(xhtml):
xhtml = regex.sub(r"“", r"<ldq>", xhtml)
xhtml = regex.sub(r"”", r"<rdq>", xhtml)
xhtml = regex.sub(r"‘", r"<lsq>", xhtml)
xhtml = regex.sub(r"<rdq> ’(\s+)", r"<rdq> <rsq>\1", xhtml)
xhtml = regex.sub(r"<rdq> ’</", r"<rdq> <rsq></", xhtml)
xhtml = regex.sub(r"([\.\,\!\?\…\:\;])’", r"\1<rsq>", xhtml)
xhtml = regex.sub(r"—’(\s+)", r"—<rsq>\1", xhtml)
xhtml = regex.sub(r"—’</", r"—<rsq></", xhtml)
xhtml = regex.sub(r"([a-z])’([a-z])", r"\1<ap>\2", xhtml)
xhtml = regex.sub(r"(\s+)’([a-z])", r"\1<ap>\2", xhtml)
xhtml = regex.sub(r"<ldq>", r"‘", xhtml)
xhtml = regex.sub(r"<rdq>", r"’", xhtml)
xhtml = regex.sub(r"<lsq>", r"“", xhtml)
xhtml = regex.sub(r"<rsq>", r"”", xhtml)
xhtml = regex.sub(r"<ap>", r"’", xhtml)
xhtml = regex.sub(r"’ ’", r"’ ”", xhtml) #Correct a common error
return xhtml
if __name__ == "__main__":
main()