Приложение к «Python в библиотеке» — страница 6 из 7

fb2_list.py

#!/usr/bin/env python

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

import sys, os

import zipfile

# Извлечение из архивов в папке

# Изготовление списка книг в текущей папке

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

List = []

Count = 0

def parse_zip(fn): # обработка zip

, ,global path

, ,global Count

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

, ,z.extractall(path)

, ,Count += 1

def parse_file(fn): # обработка файла

, ,m = fn.split(".")[-1]

, ,if (m == "zip"): # если zip

, , , ,parse_zip(fn)

, , , ,

def parse_dir(fn): # сканирование папки

, ,dirlist = os.listdir(fn)

, ,dirlist.sort()

, ,for a in dirlist:

, , , ,if os.path.getsize(a) > 0:

, , , , , , , ,parse_file(a)

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

def SaveList():

, ,f = open('list.txt', 'w', encoding="utf-8")

, ,for i in List:

, , , ,f.write(i)# 'cp1251' '\n'

, ,f.close()

def ScanDir(fn): # сканирование папки

, ,dirlist = os.listdir(fn)

, ,dirlist.sort()

, ,for a in dirlist:

, , , ,if not os.path.isdir(a):

, , , , , ,a = a.lower()

, , , , , ,m = a.split(".")[-1]

, , , , , ,if (m == "fb2"): # , , , , , , , , or (m == "zip")

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

, , , , , , , ,List.append(a+'\n')

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

path = os.getcwd()

parse_dir(path) # сканирование текущей папки

print('Файлов извлечено '+str(Count))

ScanDir(path)

SaveList()

print('ok??')

join_fb2m2.py

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import sys, os

# 18.01.22

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

def SaveList():

, ,f = open('lib.fb2', 'w', encoding="utf-8")

, ,for i in Books:

, , , ,f.write(i)# 'cp1251' '\n'

, ,f.close()

Books = []

conutBooks = 0

LAllNotes = []

'''

def AddNotes(LNotes):

, ,if len(LNotes) > 0:

, , , ,f = open('Notes'+str(conutBooks)+'.txt', 'w', encoding="utf-8")

, , , ,for i in LNotes:

, , , , , ,i = i.replace('id="n','id="'+ str(conutBooks)+ '_n')

, , , , , ,f.write(i)

, , , ,f.close()

'''

def AddNotes(LNotes):

, ,if len(LNotes) > 0:

, , , ,for i in LNotes:

, , , , , ,i = i.replace('id="n','id="'+ str(conutBooks)+ '_n')

, , , , , ,LAllNotes.append(i)

def addFb2(fn, first):

, ,global Books

, ,global conutBooks

, ,LList = []

, ,sBook_title = ''

, ,bBook_title = False

, ,bWait_notes = False

, ,bNotes = False

, ,LNotes = []

, ,conutBooks += 1

, ,if os.path.isfile(nfile):

, , , ,with open(fn, encoding="utf8") as f:

, , , , , ,LList = f.readlines()

, , , ,for i in LList:

, , , , , ,if bNotes:

, , , , , , , ,if i.find(' -1:

, , , , , , , , , ,AddNotes(LNotes)

, , , , , , , , , ,break

, , , , , , , ,else:

, , , , , , , , , ,LNotes.append(i)

, , , , , , , ,continue

, , , , , ,if bWait_notes:

, , , , , , , ,if i.find(' -1:

, , , , , , , , , ,bNotes = True

, , , , , , , , , ,LNotes.append(i)

, , , , , , , ,if i.find(' -1:

, , , , , , , , , ,break

, , , , , , , ,continue

, , , , , ,if not first: #

, , , , , , , ,if bBook_title:

, , , , , , , , , ,n = i.find('

, , , , , , , , , ,if ( n == -1):

, , , , , , , , , , , ,sBook_title = sBook_title + ' ' + i.strip()

, , , , , , , , , , , ,continue

, , , , , , , , , ,else:

, , , , , , , , , , , ,sBook_title = sBook_title + ' ' + i[:n]

, , , , , , , , , , , ,bBook_title = False

, , , , , , , , , , , ,

, , , , , , , ,n = i.find('

, , , , , , , ,if n > -1:

, , , , , , , , , ,sBook_title = i[n+12:]

, , , , , , , , , ,n = sBook_title.find('

, , , , , , , , , ,if n > -1:

, , , , , , , , , , , ,sBook_title = sBook_title[:n]

, , , , , , , , , , , ,bBook_title = False

, , , , , , , , , ,else:

, , , , , , , , , , , ,sBook_title = sBook_title + ' ' + i.strip()

, , , , , , , , , , , ,bBook_title = True

, , , , , , , , , , , ,continue

, , , , , , , ,n = i.find('

, , , , , , , ,if n > -1:

, , , , , , , , , ,i = i[n:]

, , , , , , , , , ,n = i.find('>')

, , , , , , , , , ,i = i[n+1:]

, , , , , , , , , ,

, , , , , , , , , ,Books.append('\n*%%%%%%%* '+str(conutBooks)+'\n')

, , , , , , , , , ,#print('%%%%%%%')

, , , , , , , , , ,bb = sBook_title.strip()

, , , , , , , , , ,#print(bb)

, , , , , , , , , ,Books.append('

'+bb+'\n

')

, , , , , , , , , ,Books.append(i)

, , , , , , , , , ,first = True

, , , , , ,else:

, , , , , , , ,n = i.find('

, , , , , , , ,if n > -1:

, , , , , , , , , ,i = i[:n]

, , , , , , , , , ,Books.append(i)

, , , , , , , , , ,#break

, , , , , , , , , ,bWait_notes = True

, , , , , , , ,else:

, , , , , , , , , ,if i.find('-1:

, , , , , , , , , , , ,i = i.replace('href="#','href="#'+ str(conutBooks)+ '_')

, , , , , , , , , ,Books.append(i)

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

nfile = "list.txt"

first = True

if os.path.isfile(nfile): # encoding='cp1251'

with open(nfile, encoding="utf8") as f:

, , Li = f.readlines()

for i in Li:

, , addFb2(i.strip(), first)

, , first = False

, ,

Books.append('\n')

if len(LAllNotes) > 0:

, ,Books.append('\n')

, ,Books.append('<p>Примечания</p>\n')

, ,for i in LAllNotes:

, , , ,Books.append(i)

, ,Books.append('\n')

, ,

Books.append('\n')#

SaveList()

print( 'Done!')

Other

count_fb_z.py

#!/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!!!')

delbylist.py

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import sys, os

# 2 авг

#

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

L = []

co = 0

#--------------------------------------- , ,

def LoadFile(fn, Li): # Загрузка из файла в список

, ,if os.path.isfile(fn):

, , , ,f = open(fn,'r')

, , , ,for i in f:

, , , , , ,Li.append(i)

, , , ,f.close()

, ,else:

, , , ,print('I need '+ fn)

, , , ,exit()

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

def myDelFile(L):

, ,global co

, ,for i in L:

, , , ,n = i.strip()

, , , ,if os.path.isfile(n):

, , , , , ,os.remove(n)

, , , , , ,co += 1

, , , ,else:

, , , , , ,print(n)

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

path = os.getcwd()

ln = len(path) + 1

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

LoadFile('ddel.txt', L)

myDelFile(L)

print( 'Done '+ str(co))

dir_fb2.py

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import sys, os

# конвертация папки с файлами в структуру fb2

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

List = []

#---

def SaveList(fn, L):

, ,f = open(fn, 'w', encoding="utf-8")

, ,for i in L:

, , , ,f.write(i)

, ,f.close()

#**************************************************

def my_str(s):

, ,s=s.replace('\t',' , ,')

, ,s=s.replace(' ',' , ,')

, ,s=s.replace('**','>')# вставьте вместо ** символ "больше"

, ,s=s.replace('**','<')# вставьте вместо ** символ "меньше"

# s = s.rstrip

, ,s = '

' + s + '

\n'

, ,return s

, ,

def parse_file(ph):

, ,global List

, ,si = os.path.getsize(ph)

, ,if si > 0:

, , , ,List.append('

\n') , , , ,

, , , ,List.append('<p>' + os.path.basename(ph)+ '</p>\n')

, , , ,f =open(ph, encoding="utf-8")

, , , ,Li=f.readlines()

, , , ,for i in Li:

, , , , , ,s = my_str(i)

, , , , , ,List.append(s)

, , , ,f.close()

, , , ,List.append('

\n')

, ,

def parse_dir(ph):

, ,global List

, ,dirlist = os.listdir(ph)

, ,if len(dirlist) > 0:

, , , ,List.append('

\n') , , , ,

, , , ,List.append('<p>' + os.path.basename(ph)+ '</p>\n')

, , , ,

# , , dirlist.sort()

, , , ,for i in dirlist:

, , , , , ,m = os.path.join(ph, i)

, , , , , ,if os.path.isdir(m):

, , , , , , , ,parse_dir(m)

, , , , , ,else:

, , , , , , , ,parse_file(m)

, , , ,List.append('

\n')

def GetHead(myFile):

, ,global List

, ,f =open(myFile, encoding="utf-8")

, ,Li=f.readlines()

, ,for i in Li:

, , , ,List.append(i)

, ,f.close()

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

path = os.getcwd()

folder = 'Arc'

if not os.path.isdir(folder):

, ,sys.exit(folder + ' - does not exist')

myFolder = os.path.join(path, folder)

myFile = os.path.join(myFolder, 'head.txt')

if os.path.isfile(myFile):

, ,GetHead(myFile)

List.append('\n

\n')

List.append('<p>'+folder)</p><p>List.append('</p>\n')

myFile = os.path.join(myFolder, 'list.txt')

if os.path.isfile(myFile):

, ,f =open(myFile, encoding="utf-8")

, ,Li=f.readlines()

, ,for i in Li:

, , , ,i = i.strip()

, , , ,if i == '':

, , , , , ,continue

, , , ,m = os.path.join(myFolder, i)

, , , ,if os.path.isdir(m):

, , , , , ,parse_dir(m)

, , , ,else:

, , , , , ,if os.path.isfile(m):

, , , , , , , ,parse_file(m) , , , ,

, ,f.close()

List.append('

\n')

List.append('')

List.append('')

SaveList('fb.fb2', List)

print( 'Done!')

fb2err_file.py

#!/usr/bin/env python

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

import sys, os

# проверка структуры файла fb2

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

file = 'mesto_pod_solncem.fb2'

count = 0 # счетчик строк

flag = False # признак анализа тега

S = '' # место для обработанного тега

Tag = '' # место для тега

L = [] # стек

'''

with open(file, encoding="utf8") as f:

, ,LList = f.readlines()

for i in LList:

, ,count += 1

, ,if i.find('section') > -1:

, , , ,print(count)

, , , ,print(i)

f.close()

'''

count = 0 # счетчик строк

f = open(file, 'rb') # комментарий ниже

d = f.read()

for n in d:

, ,if n == 10: # символ завершения строки

, , , ,count += 1 # + в счетчик строк

, ,elif chr(n) == '<': # начало тега

, , , ,flag = True

, , , ,Tag = '' # подготовка места для тега

, ,else:

, , , ,if flag: # читаем тег

, , , , , ,if chr(n) == '>': # провека на конец тега, если да:

, , , , , , , ,S = Tag.split(' ')[0] # отбрасывание возможных параметров

, , , , , , , ,flag = False

, , , , , , , ,if S[0] == '/': # проверка на закрывающий тег

, , , , , , , , , ,S = S[1:] # удаление слеша

, , , , , , , , , ,Lo = L.pop() # чтение из стека

, , , , , , , , , ,if Lo[0] != S: # сообщение об ошибке

, , , , , , , , , , , ,print('Teg = "'+Lo[0]+'" begin in str = '+ str(Lo[1]+1))

, , , , , , , , , , , ,print('Не соответствует')

, , , , , , , , , , , ,print('Teg ="' +S+ '"end in str = '+ str(count +1))

, , , , , , , , , , , ,f.close()

, , , , , , , , , , , ,sys.exit()

, , , , , , , ,else:

, , , , , , , , if Tag[-1] != '/': # обработка одинарных тегов

, , , , , , , , , , Lo = [S, count] # подготовка для записи в стек

, , , , , , , , , , L.append(Lo) # запись в стек

, , , , , ,else:

, , , , , , , ,Tag = Tag + chr(n) # добавление символа к тегу

f.close()

print('OK!!!') # сообщение об удачной проверке.

rename2number.py

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import sys, os

# 7 avg

# Переименование всех файлов в цифру

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

count = 0

pref = '' # при желании вставить префикс к имени файла

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

def rename_fb2(old, ph):

, ,global count

, ,count +=1

# вставить проверку существования файла с выбором следующего имени файла

, ,os.rename(old,os.path.join(ph, pref + str(count)+'.fb2'))

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

def rename_zip(old, ph):

, ,global count

, ,count +=1

# вставить проверку существования файла с выбором следующего имени файла

, ,os.rename(old,os.path.join(ph, pref + str(count)+'.fb2.zip'))

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

def rename_file(adr, ph):

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

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

, , , , rename_zip(adr, ph)

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

, , , , rename_fb2(adr, ph)

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

def scan_dir(ph):

, ,global L

, ,dirlist = os.listdir(ph)

, ,dirlist.sort()

, ,for i in dirlist:

, , , ,adr = os.path.join(ph, i)

, , , ,if os.path.isdir(adr):

, , , , , ,scan_dir(adr)

, , , ,else:

, , , , , ,rename_file(adr, ph)

#********************************************************

path = os.getcwd()

scan_dir(path)

, ,

print( 'Done!')

script_con.txt