Sentence = "the heart was made to be broken"
Pythonを使用して別の行に表示するために文を分割する方法は? (1 行あたり 4 語)
Line1: the heart was made
Line2: to be broken
何かアドバイス?
Sentence = "the heart was made to be broken"
Pythonを使用して別の行に表示するために文を分割する方法は? (1 行あたり 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