2013-03-17 133 views
1

在大多数情况下,它完成了这项工作,但有时(我很难精确,它依赖于什么)落入无限循环,因为它不切分文本字符串。为什么在Python( n)中更改字符串中的行不起作用?

def insertNewlines(text, lineLength): 
    """ 
    Given text and a desired line length, wrap the text as a typewriter would. 
    Insert a newline character ("\n") after each word that reaches or exceeds 
    the desired line length. 

    text: a string containing the text to wrap. 
    line_length: the number of characters to include on a line before wrapping 
     the next word. 
    returns: a string, with newline characters inserted appropriately. 
    """ 

    def spacja(text, lineLength): 
     return text.find(' ', lineLength-1) 

    if len(text) <= lineLength: 
     return text 
    else: 
     x = spacja(text, lineLength) 
     return text[:x] + '\n' + insertNewlines(text[x+1:], lineLength) 

作品与我想除了

insertNewlines('Random text to wrap again.', 5) 

所有案件和

insertNewlines('mubqhci sixfkt pmcwskvn ikvoawtl rxmtc ehsruk efha cigs itaujqe pfylcoqw iremcty cmlvqjz uzswa ezuw vcsodjk fsjbyz nkhzaoct', 38) 

我不知道为什么。

+0

也许张贴了insertNewlines将herlp代码... – ennuikiller 2013-03-17 12:50:27

回答

5

不要重新发明轮子,用textwrap library代替:在没有空间已经发现spacja返回-1

import textwrap 

wrapped = textwrap.fill(text, 38) 

自己的代码不处理的情况。

+0

您可能意味着'textwrap.fill()'。 – jfs 2013-03-17 12:58:26

+0

@ J.F.Sebastian:的确,'.wrap()'返回一个列表,'.fill()'用换行符连接它们。 – 2013-03-17 13:00:01

1

找不到返回-1(即未找到)的情况。

尝试:

if len(text) <= lineLength: 
    return text 
else: 
    x = spacja(text, lineLength) 
    if x == -1: 
     return text 
    else: 
     return text[:x] + '\n' + insertNewlines(text[x+1:], lineLength) 
+0

谢谢你,这就是我所需要的,没有看到 – user2179212 2013-03-17 21:58:45

+0

不客气;-) – uselpa 2013-03-18 16:36:30

相关问题