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
| # -*- coding: utf-8 -*-
# Python
import os, sys, fileinput, shutil, re
input_dir = "/dir"
# liste des chapitres avec le numéro de première page et le nom de fichier correspondant
ChapNameByPage = (
(1, "002Avant-Propos.htm"),
(5, "003_introduction.htm"),
(27, "01_Part1chap1.htm"),
(46, "02_Part1chap2.htm"),
(71, "03_Part1chap3.htm"),
(89, "04_Part2chap4.htm"),
(102, "05_Part2chap5.htm"),
(126, "06_Part2chap6.htm"),
(153, "07_Part3chap7.htm"),
(168, "08_Part3chap8.htm"),
(194, "09_Part3chap9.htm"),
(217, "10_Part4chap10.htm"),
(237, "11_Part4chap11.htm"),
(255, "12_Part4chap12.htm"),
(269, "13_Conclusion.xhtml"),
(273, "14_PostFace.xhtml"),
(281, "99_Annexe.htm"),
(299, "991_Bibliographie.htm"),
(321, "Index.xhtml"),
(340, "Max") # Pour ne pas générer d'erreur pour les pages > 321
)
def repl(var):
PageNum = int(var.group(0))
Les ancres de numéros de page sont à 3 chiffres ("005")
if ChapNameByPage[0][0] <= PageNum <= ChapNameByPage[-1][0] -1:
ChapId = 0
if PageNum < 10:
ZeroFill = "00"
elif PageNum < 100:
ZeroFill = "0"
else:
ZeroFill = ""
# Parcourt la liste des chapitres jusqu'à trouver celui qui correspond, puis renvoie le tag url
while ChapId < ChapNameByPage[ChapId][0]:
if ChapNameByPage[ChapId][0] <= PageNum < ChapNameByPage[ChapId + 1][0]:
return '<a href="../Text/%s#P%s%d">%d</a>' % (ChapNameByPage[ChapId][1], ZeroFill, PageNum, PageNum)
ChapId = ChapId + 1
else:
print "Page number out of range"
# Ouverture du fichier
input_file = open(input_dir + "/file.txt", "rb")
file_content = unicode(input_file.read(), "utf-8")
input_file.close()
# C'est ici que tout se joue avec "repl" qui est la fonction et qui reçoit comme argument le match
output_text = re.sub("\d+", repl, file_content)
output_file = open(input_dir + "/file.txt", "r+b")
output_file.read() # we do this way to preserve file creation date
output_file.seek(0)
output_file.write(output_text.encode("utf-8"))
output_file.truncate()
output_file.close() |
Partager