Skip to content

Instantly share code, notes, and snippets.

@rubyu
Last active December 17, 2015 06:29
Show Gist options
  • Save rubyu/5565984 to your computer and use it in GitHub Desktop.
Save rubyu/5565984 to your computer and use it in GitHub Desktop.
Python path_to\fix_chainlp_epub.py "%1" "Fixed_%~nx1"
# -*- coding: utf-8 -*-
import argparse
from zipfile import ZipFile
from StringIO import StringIO
from io import TextIOWrapper
def get_arg():
parser = argparse.ArgumentParser(prog="fix_chainlp_epub.py",
description="fixes some issues of EPUB published by ChainLP")
parser.add_argument("input")
parser.add_argument("output")
return parser.parse_args()
def add_toc(text):
new = StringIO()
old = TextIOWrapper(text, encoding="utf-8")
line = old.readline()
while line:
if line.startswith("<spine"):
print "spine element found ...",
line = line.replace(">", " toc=\"ncx\">")
print "fixed."
new.write(line.encode("utf-8"))
new.write("\r\n")
line = old.readline()
return new.getvalue()
if __name__ == "__main__":
arg = get_arg()
print "inout: %s" % arg.input
print "output: %s" % arg.output
with ZipFile(arg.input, "r") as old, ZipFile(arg.output, "w") as new:
for info in old.infolist():
if info.filename == "metadata.opf":
text = add_toc(old.open(info))
else:
text = old.read(info)
new.writestr(info, text)
print "done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment