перенос текстового файла таким образом, чтобы каждая строка содержала максимум 80 символов - PullRequest
0 голосов
/ 27 марта 2012

есть лучший способ решить эту проблему, желательно не через модуль.

вопрос:

Обработка текста.Вы устали видеть строки в переносе электронной почты, потому что люди вводят слишком длинные строки для вашего приложения для чтения почты.Создайте программу для сканирования текстового файла на все строки длиной более 80 символов.Для каждой из ошибочных строк найдите ближайшее слово перед 80 символами и разбейте там строку, вставив оставшийся текст в следующую строку (и нажав предыдущую следующую строку вниз на одну).Когда вы закончите, не должно быть строк длиной более 80 символов.

пусть содержимое 9-16.txt:

Text Processing. You are tired of seeing lines on your e-mail wrap because people type lines that are too long for your mail reader application. Create a program to scan a text file for all lines longer than 80 characters. For each of the offending lines, find the closest word before 80 characters and break the line there, inserting the remaining text to the next line (and pushing the previous next line down one). When you are done, there should be no lines longer than 80 characters.

моя программа длядостигните этого

f=open('9-16.txt','r')

lis=[]
def ding(a):

    if len(a)<=80:
        lis.append(a)
        return
    else:
        if a[79]==' ':

            lis.append(a[:80])
            ding(a[80:])

        elif a[79]!=' ':
            ind=a.rfind(' ',0,79)

            lis.append(a[:ind+1])
            ding(a[ind+1:])

for x in f:
    if len(x)>80:
        ding(x)
    else:
        lis.append(x)

ty=open('9-16o.txt','w')
for x in lis:
    if x[-1]==' ':
        x=x[:-1]+'\n'
    else :
        x+='\n'    
    ty.write(x)
f.close()
ty.close()

9-16o.txt теперь содержит:

Text Processing. You are tired of seeing lines on your e-mail wrap because
people type lines that are too long for your mail reader application. Create a
program to scan a text file for all lines longer than 80 characters. For each
of the offending lines, find the closest word before 80 characters and break
the line there, inserting the remaining text to the next line (and pushing the
previous next line down one). When you are done, there should be no lines
longer than 80 characters.

1 Ответ

8 голосов
/ 27 марта 2012

Вот довольно простое и лаконичное решение с использованием регулярных выражений, оно, вероятно, не подойдет для вашей домашней работы, но должно быть достаточно понятно, почему ограничение использования модулей нежелательно:

import re

s = 'Text Processing. You are tired of seeing lines on your e-mail wrap because people type lines that are too long for your mail reader application. Create a program to scan a text file for all lines longer than 80 characters. For each of the offending lines, find the closest word before 80 characters and break the line there, inserting the remaining text to the next line (and pushing the previous next line down one). When you are done, there should be no lines longer than 80 characters.'
print '\n'.join(line.strip() for line in re.findall(r'.{1,80}(?:\s+|$)', s))

Результат:

Text Processing. You are tired of seeing lines on your e-mail wrap because
people type lines that are too long for your mail reader application. Create a
program to scan a text file for all lines longer than 80 characters. For each of
the offending lines, find the closest word before 80 characters and break the
line there, inserting the remaining text to the next line (and pushing the
previous next line down one). When you are done, there should be no lines longer
than 80 characters.

Ваш образец текста представляет собой одну строку, вы, вероятно, на самом деле хотите использовать что-то вроде этого:

def split_lines(text):
    lines = text.split('\n')
    regex = re.compile(r'.{1,80}(?:\s+|$)')
    return '\n'.join(s.rstrip() for line in lines for s in regex.findall(line))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...