2017-10-29 8 views
0

ファイルに保存する長い文字列があります。言葉はスペースで区切られています。長い文字列の単語の合計は3で割り切れます。ひねりのあるn文字未満の文字列を分割する方法

基本的に私は文字列を塊に分割する方法を探しています。各チャンクはn文字未満であり、チャンク内の単語数も3で割り切れる。

>>> longstring = "This is a very long string and the sum of words is divisible by three" 
>>> len(longstring.split()) 
>>> 15 

は最大行の長さがn = 30であると言う:

>>>split_string(longstring, 30) 
['This is a very long string', 'and the sum of words is', 'divisible by three'] 

まとめ:

  1. ルールは以下のとおりです。Noライン長n文字より。
  2. 新しい行にはそれぞれ3つの単語の倍数が必要です。 、

は、これまでのところ私はtextwrapを使用してみましたが、私は、文字列内の単語の合計数は常に3で割り切れることが確実な場合2.

import textwrap  
textwrap.fill(long_line, width=69) 
+0

私はあなたの第2条件が常に可能であるとは確信していません。どのように10ワードの行を3の倍数の行に分割しますか? 3の倍数の入力を保証されていますか? –

+0

文字列内の単語の総数は3で割り切れます。 – ad1v7

+0

文字列を単語に分割し、各単語に対して現在の文を長すぎるかどうかをテストします。そうであれば、現在の文をフリーズし、その語を次の行の先頭として使用します。 –

答えて

1

を実装する方法がわかりません次のようなことができます:

import sys 
#long string; 84 words; divisible by 3 
longString = "The charges are still sealed under orders from a federal judge. Plans were prepared Friday for anyone charged to be into custody as soon as Monday, the sources said. It is unclear what the charges are. A spokesman for the special counsel's office declined to comment. The White House also had no comment, a senior administration official said Saturday morning. A spokesman for the special counsel's office declined to comment. The White House also had no comment, a senior administration official said Saturday morning." 
#convert string to list 
listOfWords = longString.split() 
#list to contain lines 
lines = [] 
#make sure number of words is divisible by 3 
if len(listOfWords) % 3 != 0: 
    #exit 
    print "words number is not divisible by 3" 
    sys.exit() 
#keep going until list is empty 
while listOfWords: 

    i = 0 
    line = "" 
    #loop for every line 
    while True: 
     #puts the next 3 words into a string 
     temp = " ".join(listOfWords[i:i+3]) 
     #check new length of line after adding the new 3 words, if it is still less than 70, add the words, otherwise break out of the loop 
     if len(line) + len(temp) > 70: 
      break 
     line += "{} ".format(temp) 
     i+=3 
    #remove finished words from the list completely 
    listOfWords = listOfWords[i:] 
    #adds line into result list 
    lines.append(line.strip()) 

#to make sure this works 
for line in lines: 
    print len(str(line)) 
    print "Number of words: {}".format(len(line.split())) 
    print "number of chars: {}".format(len(line)) 
    print line 
    print "----------------------------------------" 
関連する問題