Читаем Приложение к «Python в библиотеке» полностью

Приложение к «Python в библиотеке»

Запустив скрипт «fb2_dir.py» Вы извлечете из файла исходники сакриптов.

w cat

Программирование, программы, базы данных18+

Arch

read_me.txt

Здравствуйте.

Данный файл является приложением к опусу «Python в библиотеке». Здесь собраны основные скрипты упомянутые в учебнике.

Основная «фишка» данного текста такая: «легким движением» выполнения скрипта «fb2_dir.py» содержимое этого файла скопируется в папки и файлы со скриптами.

Т.е. при успешном выполнении нижеследующих действий в Вашем распоряжении появятся исходные коды скриптов.

Действия следующие:

1. любым способом скопируйте скрипт «fb2_dir.py» из файла fb2 в отдельный файл.

2. замените блоки « , ,» на блок из четырех пробелов.

3. поместите данный файл и скрипт «fb2_dir.py» в отдельную папку (желательно).

4. запустите скрипт. Если все сделано правильно, появится папка с исходниками

5. вполне разумно ВЫ можете опасаться злонамеренных действий ужасного хакера w_cat.

Предварительно внимательно проверьте предлагаемые скрипты, от этого все только выиграют.

w_cat

PS

Да, ежели не будет протестов от читателей, я намереваюсь регулярно обновлять этот файл, пополняя и исправляя его содержимое.

13.07.2022

fb2_dir.py

#!/usr/bin/env python

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

import sys, os

# преобразование файла fb2 в каталог с папками и файлами

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

stack = []

List = []

#---

def SaveList(fn, L):

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

, ,for i in L:

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

, ,f.close()

def my_str(s):

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

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

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

, ,return s

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

path = os.getcwd()

cur_dir = path

fb2_file = 'fb.fb2'

if not os.path.isfile(fb2_file):

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

folder = False

text_f = False

Other = False

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

Li=f.readlines()

for i in Li:

, ,if Other:

, , , ,if i.find('

, , , , , ,Other = False

, , , ,continue

, ,if text_f:

, , , ,if i.find('

, , , , , ,text_f = False

, , , , , ,SaveList(file_name, List)

, , , ,elif i.find('

')==0:

, , , , , ,s = i[10:-13]

, , , , , ,file_name = os.path.join(cur_dir, s)

, , , ,elif i.find('

')>-1:

, , , , , ,i = ''

, , , ,else:

, , , , , ,List.append(i[3:]) , ,

, , , ,continue

, , , ,

, ,if folder:

, , , ,if i.find('

')==0:

, , , , , ,s = i[10:-13]

, , , , , ,cur_dir = os.path.join(cur_dir, s)

, , , , , ,stack.insert(0,cur_dir)

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

, , , , , , , ,sys.exit(cur_dir + ' - exists')

, , , , , ,os.mkdir(cur_dir)

, , , , , ,folder = False

, , , ,continue

, ,if i.find('

, , , ,if i.find('type="d"')> -1:

, , , , , ,folder = True

, , , ,else:

, , , , , ,if i.find('type="f"')> -1:

, , , , , , , ,text_f = True

, , , , , , , ,List.clear()

, ,if i.find('

, , , ,if len(stack)>0:

, , , , , ,stack.pop(0)

, , , , , ,if len(stack)>0:

, , , , , , , ,cur_dir = stack[0]

print( 'Done!')

Конец скрипта fb2_dir.py

3

spas2.py

#!/bin/env python

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

# replacing spaces with dots

import sys, os

path = os.getcwd()

def work():

new_List = [] #

old_List = []

new_List.clear() #

old_List.clear()

print('')

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

fn1=os.path.join(path, FN)

base=os.path.splitext(FN)[0]

fb2_file=open(fn1,'r')

old_List=fb2_file.readlines()

fb2_file.close()

n = 0

for item in old_List:

, , n += 1

, , s='|'+item

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

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

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

, , s = "{0:2d}{1:s}".format(n,s)

, , new_List.append(s)

fn2=os.path.join(path, base)+".txt"

new_file=open(fn2,'w')

for item in new_List:

, , new_file.write(item)

new_file.close()

print('Done')

while True:

work() # Exit => Ctrl + C

_my_zip.py

#!/usr/bin/env python

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

# Упаковка файлов fb2 в архивы zip

import sys, os

import zipfile

co = 0

def parse_file(FileName):

, ,global co

, ,fn = os.path.basename(FileName)

# , ,print fn+'.zip'

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

, ,z.write(fn)

, ,z.close()

, ,os.remove(FileName)

, ,co += 1

def parse_dir(fn):

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

# , , , ,print fn

, , , ,if (m == 'fb2'):

, , , , , ,parse_file(fn)

, , , , , ,

, , , , , ,

path = os.getcwd()

Перейти на страницу:

Похожие книги

Programming with POSIX® Threads
Programming with POSIX® Threads

With this practical book, you will attain a solid understanding of threads and will discover how to put this powerful mode of programming to work in real-world applications. The primary advantage of threaded programming is that it enables your applications to accomplish more than one task at the same time by using the number-crunching power of multiprocessor parallelism and by automatically exploiting I/O concurrency in your code, even on a single processor machine. The result: applications that are faster, more responsive to users, and often easier to maintain. Threaded programming is particularly well suited to network programming where it helps alleviate the bottleneck of slow network I/O. This book offers an in-depth description of the IEEE operating system interface standard, POSIX (Portable Operating System Interface) threads, commonly called Pthreads. Written for experienced C programmers, but assuming no previous knowledge of threads, the book explains basic concepts such as asynchronous programming, the lifecycle of a thread, and synchronization. You then move to more advanced topics such as attributes objects, thread-specific data, and realtime scheduling. An entire chapter is devoted to "real code," with a look at barriers, read/write locks, the work queue manager, and how to utilize existing libraries. In addition, the book tackles one of the thorniest problems faced by thread programmers-debugging-with valuable suggestions on how to avoid code errors and performance problems from the outset. Numerous annotated examples are used to illustrate real-world concepts. A Pthreads mini-reference and a look at future standardization are also included.

David Butenhof

Программирование, программы, базы данных