К книге
Приложение к «Python в библиотеке»Arch. Other. count_fb_z.py
85%
Arch. Other. count_fb_z.py
29

#!/usr/bin/env python

# -*- codning: utf-8 -*-

import sys, os

import zipfile

import xml.dom.minidom

# Подсчет числа секций и числа символов в fb2

#----------------------------------------------

path = os.getcwd()

count_s = 0

count_t = 0

count_b = 0

#-------------------------------------

def sect(el):

, ,global count_s

, ,global count_t

, ,childList=el.childNodes

, ,for child in childList:

, , , ,if child.nodeName == 'p':

, , , , , ,text = child.childNodes[0].nodeValue

, , , , , ,if text != None:

, , , , , , , ,count_t += len(text)

, , , ,if child.nodeName == 'section':

, , , , , ,count_s += 1

, , , , , ,sect(child)

#---------------------------------------

def parse_fb2(fn):

, ,global count_b , ,

, ,dom = xml.dom.minidom.parse(fn);

, ,dom.normalize()

, ,n_body=dom.getElementsByTagName("body")[0]

, ,sect(n_body)

, ,fb=dom.getElementsByTagName("FictionBook")[0]

, ,childList=fb.childNodes

, ,for child in childList:

# , , print(child.nodeName)

, , , , if child.nodeName == 'binary':

, , , , , ,text = child.childNodes[0].nodeValue

, , , , , ,if text != None:

, , , , , , , ,count_b += len(text)

def MyPrint(adr):

, ,print(adr)

, ,print('section '+str(count_s))

, ,print('text '+str(count_t))

, ,print('pic '+str(count_b))

, ,print('size file '+ str(os.path.getsize(adr)))

def parse_zip(adr):

, ,z = zipfile.ZipFile(adr, 'r')

, ,filelist = z.namelist()

, ,filelist.sort()

, ,for n in filelist:

, , , ,if n[-4:] == ".fb2":

, , , , , ,parse_fb2(z.open(n))

def parse_file(adr):

, ,if not os.path.isfile(adr):

, , , ,print('File not exists')

, , , ,return

, ,m = adr.split(".")

, ,if (m[-1] == "zip") and (m[-2] == "fb2"):

, , , , parse_zip(adr)

, ,elif (m[-1] == "fb2"):

, , , , parse_fb2(adr)

, ,

while True:

, ,qu = input('Введите ')

# , ,qu = '6.fb2.zip'

, ,a = os.path.join(path, qu)

, ,parse_file(a)

, ,MyPrint(a) , , , , , ,

, ,print('OK!!!')

Предыдущая главаГлава 29 из 34Следующая глава