0
Sentence = "the heart was made to be broken"

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

Line1: the heart was made
Line2: to be broken

有什么建议吗?

4

5 回答 5

6
  1. 将句子变成单词列表。
  2. 将列表分成4 个单词的块。
  3. 将分区组合成行。
于 2012-05-05T17:06:46.933 回答
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
于 2012-05-05T17:11:45.203 回答
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
于 2012-05-05T17:13:11.953 回答
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
于 2012-05-05T17:24:04.023 回答
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
于 2012-05-05T17:55:59.783 回答