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

j_par.py

#!/bin/env python

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

# Объединение абзацев (версия 19.10.21)

import sys, os

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

def EndStr(s):

, ,SQ = ''

, ,for a in reversed(s):

, , , ,if a == ' ':

, , , , , ,return SQ[:-1]

, , , ,else:

, , , , , ,SQ = a+SQ

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

old_List = [] # Сюда читается

new_List = [] # Промеждуточный список

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

#FN = input('Введите имя файла:')

#fn1=path+FN

FN = '2_.txt'

fb2_file=open(FN,'r')

#fb2_file=open(FN,'r', encoding='utf-8')

old_List=fb2_file.readlines()

fb2_file.close()

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

SS = '' # Промежуточное хранение строки

FlagQ = False

i = -1

for item in old_List: # первый проход

поиск разорванных строк

, ,i += 1

, ,if i >= len(old_List):

# , , , ,new_List.append(item[i+1]) ?

, , , ,break

, ,s = item.strip()# Обрезание пробелов

, ,if s == '':

, , , ,new_List.append(s)

, , , ,continue

, ,m = ord(s[-1]) # последний символ строки

# , ,print(s)

, ,if (m > 1071 and m < 1104) or m == 44: # от "а" до "я" + ","

, , , ,if i+1 >= len(old_List):

, , , , , ,break

, , , ,d = old_List[i+1].strip()

, , , ,if (d != ''):

, , , , , ,m = ord(d[0]) # первый символ следующей строки

, , , , , ,if (m > 1071 and m < 1104): # от "а" до "я"):

, , , , , , , ,new_List.append(s+' @')# помечаем строку для объединения с последующей

, , , , , ,else:# в обычном тексте вероятность, что строка

завершится "собачкой" очено мала, но ... тогда это будет ошибочное объединение

, , , , , , , ,new_List.append(s)

, , , ,else:

, , , , , ,new_List.append(s)

, ,else:

, , , ,new_List.append(s)

old_List.clear()

#for item in reversed(new_List): # второй проход

объединение помеченных строк

for item in new_List:

, ,if item == '':

, , , ,if SS != '':

, , , , , ,old_List.append(SS)

, , , , , ,SS = ''

, , , ,old_List.append(item)

, , , ,continue

, ,if FlagQ:

, , , ,SS = SS[:-1] + item

, , , ,FlagQ = item[-1] == '@'

, ,else:

, , , ,if SS != '':

, , , , , ,old_List.append(SS)

, , , , , ,SS = ''

, , , ,if item[-1] == '@': # последний символ строки

, , , , , ,FlagQ = True

, , , , , ,SS = item

, , , ,else:

, , , , , ,old_List.append(item)

if SS != '':

, ,old_List.append(SS)

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

fn2="3_x.txt"

new_file=open(fn2,'w')

for i in old_List:

, , new_file.write(i+'\n')

new_file.close()

print('Done')

perenos.py

|#!/bin/env python

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

# Объединение абзацев разде-

# разделенных переносами

# 19.10.21

import sys, os

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

def EndStr(s):

, ,SQ = ''

, ,for a in reversed(s):

, , , ,if a == ' ':

, , , , , ,return SQ[:-1]

, , , ,else:

, , , , , ,SQ = a+SQ

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

old_List = [] # Сюда читается

new_List = [] # Промеждуточный список

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

#FN = input('Введите имя файла:')

#fn1=path+FN

FN = '1.txt'

fb2_file=open(FN,'r')

#fb2_file=open(FN,'r', encoding='utf-8')

old_List=fb2_file.readlines()

fb2_file.close()

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

SS = '' # Промежуточное хранение строки

SQ = '' # Начало слова "разор-

"разорванного" "странным" переносом

FlagQ = False

i = 0

Первый проход. Поиск "странных" переносов

for item in old_List:

, ,s = item.strip()# Обрезание пробелов

, ,if s == '':

, , , ,new_List.append(s)

, , , ,i += 1

, , , ,if i > len(old_List):

, , , , , ,new_List.append(item[i+1])

, , , , , ,break

, , , ,continue

, ,

, ,if (s[-1] == '-'): # последний символ строки

, , , ,SQ = EndStr(s) # следующая строка начинается с SQ

, , , ,if (SQ != None) and (SQ != '') and (old_List[i+1].find(SQ)==0):

, , , , , ,m = -(len(SQ)+1)

, , , , , ,new_List.append(s[:m]+'@') # помечаем строку для последующего объединения

, , , ,else:

, , , , , ,new_List.append(s)

, ,else:

, , , ,new_List.append(s)

, ,i += 1

, ,if i > len(old_List):

, , , ,new_List.append(item[i+1])

, , , ,break

old_List.clear()

# второй проход. соединение строк

#for item in reversed(new_List):

for item in new_List:

, ,if item == '':

, , , ,if SS != '':

, , , , , ,old_List.append(SS)

, , , , , ,SS = ''

, , , ,old_List.append(item)

, , , ,continue

# , ,print(item)

, ,if FlagQ:

, , , ,SS = SS[:-1] + item

, , , ,FlagQ = item[-1] == '@'

, ,else:

, , , ,if SS != '':

, , , , , ,old_List.append(SS)

, , , , , ,SS = ''

, , , ,if item[-1] == '@': # последний символ строки

, , , , , ,FlagQ = True

, , , , , ,SS = item

, , , ,else:

, , , , , ,old_List.append(item)

, , , , , , , ,

if SS != '':# запись последней строки

, ,old_List.append(SS)

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

fn2="2_.txt"

new_file=open(fn2,'w')

for i in old_List:

, , new_file.write(i+'\n')

new_file.close()

print('Done')

str2parag.py

#!/usr/bin/env python

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

import sys, os

#-- скрипт для сборки абзацев из разрозненных строк ---

s = '' # строка коию будем записывать в список

L = [] # список для хранения выходного файла

i = 0 # указатель положения в файле

def RusBukva1(n): # обработка буквы «до»

, ,return ((n > 223) and (n < 256)) or (n==44) or (n==45)

def RusBukva2(n): # обработка буквы «после»

, ,return ((n > 223) and (n < 256))

f = open('alfredr.txt', 'rb') # открываем и читаем промежуточный файл

d = f.read()

f.close()

c13 = 2 # константа индицирующая наличие символа «13»

for n in d: # проверка промежуточного файла на наличие символа «13»

, ,if (n == 13):

, , , ,c13 = 3

, , , ,break

for n in d: # основной цикл проверки файла

, ,i +=1 # инкримент указателя положения в файле

, ,if (n == 10): # если конец строки

, , , ,if RusBukva1(d[i-c13]) and RusBukva2(d[i]): # проверяем «до» и «после»

, , , , s += ' ' # в строку пробел

, , , ,else:

, , , , L.append(s) # добавляем строку в список

, , , , s='' # подготовка пустой строки

, ,else:

, , , ,if n != 13:

, , , , , ,m = d[i-1] # эта строка и 6 строк ниже объясню еще ниже

, , , , , ,if (m > 191) and (m < 256):

, , , , , , , ,m += 848

, , , , , ,elif(m==184):

, , , , , , , ,m = 1105

, , , , , ,elif (m==151):

, , , , , , , ,m = 8212

, , , , , ,s += chr(m) # запись символа в строку

f = open('outtext.txt', 'w') # выходной файл

for etem in L: # просматриваем список и записываем в файл

, ,f.write(etem+'\n')

f.close()

print('OK!!!')

utf8-1251.py

#!/usr/bin/env python

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

fin = open('art.txt', 'r') # открываем исходный файл

out = open('outt.txt', 'w', encoding='cp1251') # подготавливаем промежуточный файл

for s in fin: # переписываем из файла в файл

, ,s = s.rstrip()

, ,out.write(s+'\n')

fin.close()

out.close()

print('Done')

8 Images

base64_pic.py

#!/usr/bin/env python

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

import sys, os

import base64

def getAttribute(Tag):

, ,s = Tag[Tag.find(' id=')+4:]

, ,s = s[s.find('"')+1:]

, ,s = s[:s.find('"')]

, ,return s

def parseBinaryContent(filename):

, ,

# filename = sys.argv[1]

, ,if filename[-4:] == '.fb2':

, , , , dirname = filename[:-4]+'_pic'

, ,else:

, , , , exit()

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

, , , ,os.mkdir(dirname)

, ,flag = False

, ,bina = False

, ,S = ''

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

, ,path = os.getcwd()

, ,fin = os.path.join(path, filename)

, ,f = open(fin, 'rb')

, ,d = f.read()

, ,

, ,for n in d:

, , , ,if bina:

, , , , , ,if chr(n) == '<':

, , , , , , , ,print('5')

, , , , , , , ,dd = base64.urlsafe_b64decode(S) #()

, , , , , , , ,hh = open(os.path.join(dirname, name_Pic), 'wb')

, , , , , , , ,hh.write(dd)

, , , , , , , ,hh.close()

, , , , , , , ,bina = False

, , , , , ,else:

, , , , , , , ,S = S + chr(n)

, , , , , ,continue

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

, , , , , ,

, , , , , ,flag = True

, , , , , ,Tag = ''

, , , ,else:

, , , , , ,if flag:

, , , , , , , ,if chr(n) == '>':

, , , , , , , , , ,

, , , , , , , , , ,flag = False

, , , , , , , , , ,if Tag.find('binary')> -1:

, , , , , , , , , , # print(Tag)

, , , , , , , , , , , ,bina = True

, , , , , , , , , , , ,S = ''

, , , , , , , , , , , ,name_Pic = getAttribute(Tag)

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

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

, , , , , , , ,else:

, , , , , , , , , ,Tag = Tag + chr(n)

, , , , , ,

, , , , , , , ,

parseBinaryContent('Ho.fb2')

del_pic.py

#!/usr/bin/env python

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

# Удаление секций binary из файла xxxx.fb2.zip

import sys, os, io, zipfile

cover = ''

NameFb2 = ''

L=[]

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

def Del_Image():

, ,global NameFb2

, ,global L

, ,vi = io.StringIO()

, ,notbinary = True

, ,for i in L:

, , , ,if notbinary:

, , , , , ,if (i.find('=0):

, , , , , , , ,if (i.find(cover)>=0):

, , , , , , , , , ,vi.write(i)

, , , , , , , ,else:

, , , , , , , , , ,notbinary = False

, , , , , ,else:

, , , , , , , ,vi.write(i)

, , , ,if i.find('=0:

, , , , , ,notbinary = True

, ,w = zipfile.ZipFile('^temp.zip', 'w', zipfile.ZIP_DEFLATED) # Создание нового архива

, ,w.writestr(NameFb2, vi.getvalue()) , ,

, ,w.close()

, ,vi.close()

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

def o_zip(fn):

, ,global NameFb2

, ,global L

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

, ,filelist = z.namelist()

, ,for n in filelist:

, , , ,try:

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

, , , , , , , ,body = z.open(n)

, , , , , , , ,NameFb2 = n

, , , , , , , ,for line in body:

, , , , , , , , , ,L.append(str(line, 'UTF-8'))

, , , , , , , ,return True

, , , ,except:

, , , , , ,print( "error:", n )

, , , , , ,return False

#-------------------- main ------------------------

print('Удаление секций binary из файла xxxx.fb2.zip')

FileName = input('Введите имя файла:')

if FileName == '':

, , exit()

e = input('Удалить обложку? [y/n]')

if e == 'y':

, , cover = 'not'

else:

, , cover = 'cover.'

if os.path.isfile(FileName):

, ,if o_zip(FileName):

, , , ,Del_Image()

, , , ,os.remove(FileName)

, , , ,os.rename('^temp.zip', FileName)

, , , ,print("Done.")

, ,else:

, , , ,print("???")

else:

, ,print("File doesn't exists!")

pic_base64.py

# подготовка рисунка для fb2

import base64

# Автор: Abhishek Amin , ,Дата записи 09.04.2021

# + w_cat 05.07.22

fn = 'ce55.jpg'

with open(fn, 'rb') as binary_file:

, ,binary_file_data = binary_file.read()

, ,base64_encoded_data = base64.b64encode(binary_file_data)

, ,base64_message = base64_encoded_data.decode('utf-8')

, ,ff = fn + '.txt'

, ,f = open(ff, 'w')

, ,f.write(''+'\n')

, ,f.write(base64_message+'\n')

, ,f.write(''+'\n\n')

, ,f.close()

# осталось сделать:

# 1. определение типа файла

# , ,и изменение content-type в соответствии с типом.

# 2. упаковку группы файлов.

10