2

Ahoy StackOverlow-ers!

I have a rather trivial question but it's something that I haven't been able to find in other questions here or on online tutorials: How might we be able to format the output of a Python program that so that it fits a certain aesthetic format without any extra modules?

The aim here is that I have a block of plain text like that from a newspaper article, and I've filtered through it earlier to extract just the words I want but now I'd like to print it out in the format that each line only has 70 characters along it and any word won't be broken if it should normally fall on a line break.

Using .ljust(70) as in stdout.write(article.ljust(70)) doesn't seem to do anything to it.

The other thing about not having words broken would be as:

Latest news tragic m

urder innocent victi

ms family quiet neig

hbourhood

Looking more like this:

Latest news tragic

murder innocent

victims family 

quiet neighbourhood

Thank you all kindly in advance!

4

3 回答 3

8

签出python textwrap 模块(一个标准模块)

>>> import textwrap
>>> t="""Latest news tragic murder innocent victims family quiet neighbourhood"""
>>> print "\n".join(textwrap.wrap(t, width=20))
Latest news tragic
murder innocent
victims family quiet
neighbourhood
>>> 
于 2012-05-08T08:29:20.793 回答
0

使用 textwrap 模块:

http://docs.python.org/library/textwrap.html

于 2012-05-08T08:30:58.847 回答
0

我相信这可以改进。没有任何库:

def wrap_text(text, wrap_column=80):
    sentence = ''
    for word in text.split(' '):
        if len(sentence + word) <= 70:
            sentence += ' ' + word
        else:
            print sentence
            sentence = word
    print sentence

编辑:如果您想使用正则表达式来挑选单词,请从评论中使用:

import re

def wrap_text(text, wrap_column=80):
    sentence = ''
    for word in re.findall(r'\w+', text):
        if len(sentence + word) <= 70:
            sentence += ' ' + word
        else:
            print sentence
            sentence = word
    print sentence
于 2012-05-08T09:34:18.440 回答