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

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

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

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

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

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

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