#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys from typing import Any import lxml.etree ns = {"fb": "http://www.gribuser.ru/xml/fictionbook/2.0"} def add_em_for_annotation(annotation: Any) -> None: for p in annotation.xpath(".//fb:p", namespaces=ns): em = lxml.etree.Element("{http://www.gribuser.ru/xml/fictionbook/2.0}emphasis") em.text = p.text p.text = '' for x in p.getchildren(): em.append(x) p.append(em) def fix_fb2_file(path: str) -> None: fname = os.path.split(path)[-1] print(fname, end=": ", flush=True) fb2 = lxml.etree.parse(path) for annotation in fb2.xpath(".//fb:section/fb:annotation", namespaces=ns): add_em_for_annotation(annotation) # annotation.getparent().remove(annotation) name, ext = os.path.splitext(path) path_fixed = name + " - fixed annotations" + ext fb2.write(path_fixed, xml_declaration=True, encoding="utf-8") print("OK", flush=True) def main() -> int: for f in sys.argv[1:]: fix_fb2_file(f) return 0 if __name__ == "__main__": sys.exit(main())