Рубрики
Без рубрики

textwrap – Форматирование текстовых абзацев

Автор оригинала: Doug Hellmann.

Цель:

Форматирование текста путем настройки места разрыва строки в абзаце.

Модуль textwrap можно использовать для форматирования текста для вывода в ситуациях, когда требуется красивая печать. Он предлагает программные функции, аналогичные функциям переноса или заполнения абзацев, которые есть во многих текстовых редакторах и текстовых процессорах.

Пример данных

В примерах этого раздела используется модуль textwrap_example.py , который содержит строку sample_text .

textwrap_example.py

sample_text  '''
    The textwrap module can be used to format text for output in
    situations where pretty-printing is desired.  It offers
    programmatic functionality similar to the paragraph wrapping
    or filling features found in many text editors.
    '''

Заполнение абзацев

Функция fill () принимает текст в качестве ввода и создает форматированный текст в качестве вывода.

textwrap_fill.py

import textwrap
from textwrap_example import sample_text

print(textwrap.fill(sample_text, width50))

Результаты не совсем желательны. Теперь текст выровнен по левому краю, но первая строка сохраняет свой отступ, а пробелы в начале каждой последующей строки встроены в абзац.

$ python3 textwrap_fill.py

     The textwrap module can be used to format
text for output in     situations where pretty-
printing is desired.  It offers     programmatic
functionality similar to the paragraph wrapping
or filling features found in many text editors.

Удаление существующего отступа

В предыдущем примере в середине вывода были встроенные табуляции и лишние пробелы, поэтому он не очень четко отформатирован. Удаление общего префикса пробелов из всех строк в образце текста с помощью dedent () дает лучшие результаты и позволяет использовать строки документации или встроенные многострочные строки прямо из кода Python при удалении форматирования самого кода . Строка-образец имеет искусственный уровень отступа для иллюстрации этой функции.

textwrap_dedent.py

import textwrap
from textwrap_example import sample_text

dedented_text  textwrap.dedent(sample_text)
print('Dedented:')
print(dedented_text)

Результаты начинают выглядеть лучше.

$ python3 textwrap_dedent.py

Dedented:

The textwrap module can be used to format text for output in
situations where pretty-printing is desired.  It offers
programmatic functionality similar to the paragraph wrapping
or filling features found in many text editors.

Поскольку «dedent» – это противоположность «indent», результатом является блок текста с удаленными общими начальными пробелами из каждой строки. Если одна строка уже имеет больший отступ, чем другая, некоторые пробелы не будут удалены.

Введите как

␣Line one.
␣␣␣Line two.
␣Line three.

становится

Line one.
␣␣Line two.
Line three.

Сочетание Dedent и Fill

Затем срезанный текст можно передать через fill () с несколькими различными значениями width .

textwrap_fill_width.py

import textwrap
from textwrap_example import sample_text

dedented_text  textwrap.dedent(sample_text).strip()
for width in [45, 60]:
    print('{} Columns:\n'.format(width))
    print(textwrap.fill(dedented_text, widthwidth))
    print()

Это дает выходные данные указанной ширины.

$ python3 textwrap_fill_width.py

45 Columns:

The textwrap module can be used to format
text for output in situations where pretty-
printing is desired.  It offers programmatic
functionality similar to the paragraph
wrapping or filling features found in many
text editors.

60 Columns:

The textwrap module can be used to format text for output in
situations where pretty-printing is desired.  It offers
programmatic functionality similar to the paragraph wrapping
or filling features found in many text editors.

Блоки отступов

Используйте функцию indent () , чтобы добавить согласованный префиксный текст ко всем строкам в строке. Этот пример форматирует тот же пример текста, как если бы он был частью сообщения электронной почты, цитируемого в ответе, с использованием > в качестве префикса для каждой строки.

textwrap_indent.py

import textwrap
from textwrap_example import sample_text

dedented_text  textwrap.dedent(sample_text)
wrapped  textwrap.fill(dedented_text, width50)
wrapped  '\n\nSecond paragraph after a blank line.'
final  textwrap.indent(wrapped, '> ')

print('Quoted block:\n')
print(final)

Блок текста разделяется на новые строки, префикс добавляется к каждой строке, содержащей текст, а затем строки объединяются обратно в новую строку и возвращаются.

$ python3 textwrap_indent.py

Quoted block:

>  The textwrap module can be used to format text
> for output in situations where pretty-printing is
> desired.  It offers programmatic functionality
> similar to the paragraph wrapping or filling
> features found in many text editors.

> Second paragraph after a blank line.

Чтобы указать, какие строки получают новый префикс, передайте вызываемый объект в качестве аргумента predicate в indent () . Вызываемый объект будет вызываться по очереди для каждой строки текста, и префикс будет добавлен для строк, в которых возвращаемое значение истинно.

textwrap_indent_predicate.py

import textwrap
from textwrap_example import sample_text


def should_indent(line):
    print('Indent {!r}?'.format(line))
    return len(line.strip()) % 2  0


dedented_text  textwrap.dedent(sample_text)
wrapped  textwrap.fill(dedented_text, width50)
final  textwrap.indent(wrapped, 'EVEN ',
                        predicateshould_indent)

print('\nQuoted block:\n')
print(final)

В этом примере префикс EVEN добавляется к строкам, содержащим четное количество символов.

$ python3 textwrap_indent_predicate.py

Indent ' The textwrap module can be used to format text\n'?
Indent 'for output in situations where pretty-printing is\n'?
Indent 'desired.  It offers programmatic functionality\n'?
Indent 'similar to the paragraph wrapping or filling\n'?
Indent 'features found in many text editors.'?

Quoted block:

EVEN  The textwrap module can be used to format text
for output in situations where pretty-printing is
EVEN desired.  It offers programmatic functionality
EVEN similar to the paragraph wrapping or filling
EVEN features found in many text editors.

Висячие отступы

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

textwrap_hanging_indent.py

import textwrap
from textwrap_example import sample_text

dedented_text  textwrap.dedent(sample_text).strip()
print(textwrap.fill(dedented_text,
                    initial_indent'',
                    subsequent_indent' ' * 4,
                    width50,
                    ))

Это позволяет создать выступающий отступ, когда первая строка имеет меньший отступ, чем другие строки.

$ python3 textwrap_hanging_indent.py

The textwrap module can be used to format text for
    output in situations where pretty-printing is
    desired.  It offers programmatic functionality
    similar to the paragraph wrapping or filling
    features found in many text editors.

Значения отступа также могут включать непробельные символы. Висячий отступ может иметь префикс * , например, для создания маркеров.

Усечение длинного текста

Чтобы обрезать текст для создания сводки или предварительного просмотра, используйте shortten () . Все существующие пробелы, такие как табуляции, новые строки и серии из нескольких пробелов, будут стандартизированы до одного пробела. Затем текст будет усечен до длины, меньшей или равной запрошенной, между границами слов, чтобы не включать частичные слова.

textwrap_shorten.py

import textwrap
from textwrap_example import sample_text

dedented_text  textwrap.dedent(sample_text)
original  textwrap.fill(dedented_text, width50)

print('Original:\n')
print(original)

shortened  textwrap.shorten(original, 100)
shortened_wrapped  textwrap.fill(shortened, width50)

print('\nShortened:\n')
print(shortened_wrapped)

Если текст без пробелов удаляется из исходного текста как часть усечения, он заменяется значением заполнителя. Значение по умолчанию [...] можно заменить, предоставив аргумент placeholder для shortten () .

$ python3 textwrap_shorten.py

Original:

 The textwrap module can be used to format text
for output in situations where pretty-printing is
desired.  It offers programmatic functionality
similar to the paragraph wrapping or filling
features found in many text editors.

Shortened:

The textwrap module can be used to format text for
output in situations where pretty-printing [...]

Смотрите также