Python:是否可以将句子分成两行?

时间:2012-05-05 17:03:14

标签: python

Sentence = "the heart was made to be broken"

如何使用Python分割句子以便在单独的行中显示? (每行4个字)

Line1: the heart was made
Line2: to be broken

有什么建议吗?

5 个答案:

答案 0 :(得分:6)

答案 1 :(得分:2)

试试这个:

s = 'the heart was made to be broken'

for i, word in enumerate(s.split(), 1):
    if i % 4:
        print word,
    else:
        print word

> the heart was made
> to be broken

答案 2 :(得分:0)

这是一个解决方案:

import math

def fourword(s):
    words = s.split()
    fourcount = int(math.ceil(len(words)/4.0))
    for i in range(fourcount):
        print " ".join(words[i*4:(i+1)*4])

if __name__=="__main__":
    fourword("This is a test of fourword")
    fourword("And another test of four")

输出结果为:

>python fourword.py 
This is a test
of fourword
And another test of
four

答案 3 :(得分:0)

让我解释使用itertools模块的此问题的解决方案。当您尝试处理序列时,无论是列表或字符串还是任何其他可迭代序列,通常是从标准库中查看itertools模块的第一步

from itertools import count, izip, islice, starmap

# split sentence into words
sentence = "the heart was made to be broken".split()
# infinite indicies sequence -- (0, 4), (4, 8), (8, 12), ...
indicies = izip(count(0, 4), count(4, 4)) 
# map over indices with slicing
for line in starmap(lambda x, y: sentence[x:y], indicies):
    line = " ".join(line)
    if not line:
        break
    print line

答案 4 :(得分:0)

通用功能:

from itertools import count, groupby

def split_lines(sentence, step=4):
    c = count()
    chunks = sentence.split()
    return [' '.join(g) for k, g in groupby(chunks, lambda i: c.next() // step)]

您可以这样使用:

>>> sentence = "the heart was made to be broken"
>>> split_lines(sentence)
['the heart was made', 'to be broken']
>>> split_lines(sentence, 5)
['the heart was made to', 'be broken']
>>> split_lines(sentence, 2)
['the heart', 'was made', 'to be', 'broken']

结果你可以做任何你想做的事情(包括打印):

>>> for line in split_lines(sentence):
...     print line
...     
the heart was made
to be broken