2015-08-20 18 views
5

我有一個很長的字符串,我想將它分解爲最大X個字符。但是,只有在一個空格處(如果字符串中的某個單詞比X個字符長,就把它放到它自己的一個空格中)。將字符串拆分爲最大長度爲X的塊 - 僅在空間拆分

我甚至不知道如何開始做這個... Pythonically

僞代碼:

declare a list 
while still some string left: 
    take the fist X chars of the string 
    find the last space in that 
    write everything before the space to a new list entry 
    delete everything to the left of the space 

在我的代碼了,是有一些Python模塊,可以幫助我(我不認爲pprint可以)?

+4

我剛剛發現python有一個[textwrap](https://docs.python.org/3.5/ library/textwrap.html#module-textwrap)module;) – swenzel

回答

13

這就是我將如何處理它:首先,將文本分成單詞。從一行中的第一個單詞開始,重複其餘單詞。如果下一個單詞適合當前行,則添加它,否則結束當前行並將該單詞用作下一行的第一個單詞。重複,直到所有單詞用完。

下面是一些代碼:

text = "hello, this is some text to break up, with some reeeeeeeeeaaaaaaally long words." 
n = 16 

words = iter(text.split()) 
lines, current = [], next(words) 
for word in words: 
    if len(current) + 1 + len(word) > n: 
     lines.append(current) 
     current = word 
    else: 
     current += " " + word 
lines.append(current) 

更新:由於@swenzel在評論中指出的,其實應該是一個模塊:textwrap。這將產生與上述代碼相同的結果(並且它也將在連字符上斷開):

import textwrap 
lines = textwrap.wrap(text, n, break_long_words=False) 
+0

這看起來像是比我的更好的算法(+1) – Mawg