Sentence = "the heart was made to be broken"
如何使用 Python 拆分句子以在单独的行中显示?(每行 4 个字)
Line1: the heart was made
Line2: to be broken
有什么建议吗?
Sentence = "the heart was made to be broken"
如何使用 Python 拆分句子以在单独的行中显示?(每行 4 个字)
Line1: the heart was made
Line2: to be broken
有什么建议吗?
试试这个:
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
这是一个解决方案:
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
让我解释一下使用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
通用功能:
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