2012-05-08 115 views
2

Ahoy StackOverlow-ers!Python:如何将大文本输出格式化为'漂亮'和用户定义

我有一个相当微不足道的问题,但这是我在这里或在线教程中无法找到的其他问题:我们如何能够格式化Python程序的输出以使其适合某些美学格式没有任何额外的模块?

这里的目的是,我有一个类似于报纸文章的纯文本块,并且我已经通过它提前筛选,以提取我想要的单词,但现在我想要将它打印出来格式,每行只有70个字符,如果它通常应该在换行符上,任何单词都不会被破坏。

在stdout.write(article.ljust(70))中使用.ljust(70)似乎没有做任何事情。

约没有打破的话会因为其他的事情:

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 

谢谢所有好心提前!

+0

我觉得这是这个副本: HTTP ://stackoverflow.com/questions/250357/smart-truncate-in-python – jgritty

+1

此外,对于报纸和排版,请参阅:http://en.wikipedia.org/wiki/Kerning – jgritty

+0

没关系,textwrap看起来像一个很合适。 – jgritty

回答

8

结帐的python textwrap module(标准模块)

>>> 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 
>>> 
+0

感谢您的回答!它工作的一种享受,但我想知道如果没有textwrap模块也可以做类似的事情吗?我希望它可能需要更多的努力,但不是吗? – user1359892

+0

为什么你不使用textwrap? – Marcin

+0

如果你想为这个特定的情况编写你自己的代码,我认为这也很好。它应该不难。它将只使用标准的python函数。 –

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 
+0

谢谢,Satyajit!我将不得不放弃这一点。它看起来就像我想象的那样。而不是word.split(),你认为使用正则表达式可能会改进我在哪里以及如何分割它会好吗? – user1359892

+0

是的。如果你只想要的话,而不是标点符号(这个答案)[http://stackoverflow.com/a/1059596/504262]会有所帮助。使用''re.findall(r'\ w +',text)''。 – satran

+0

如果您发现此答案正确,请您接受它。 – satran