2017-02-21 24 views
1

1行あたりの文字数を60文字に制限する出力ファイルを書き込もうとしています。私はテキストファイルを読み込んで1行に60文字にすることができましたが、同じ行にあるとは思わない単語を追加しました。例えば、ファイルのリードは、テキストラッパー・メソッドファイル操作のためのPythonでのtextwrapperの使用方法

Albuquerque is my turkey and he's feathered and he's fine, 
And he wobbles and he gobbles and he's absolutely mine He's 

the best pet you can get yet better than a dog or cat, He's 
my albuquerque turkey and i'm awfully proud of that 

を使用した後

Albuquerque is my turkey and he's feathered and he's fine, And he 
wobbles and he gobbles and he's 
absolutely mine 

He's the best pet you can get yet better than 
a dog or cat, He's my albuquerque turkey and i'm awfully proud of that 

であり、それは私が対応するために、テキストのラッパー・メソッドを調整することができますどのように

Albuquerque is my turkey and he’s feathered and he’s fine, 
And he wobbles and he gobbles and he’s absolutely mine 

He’s the best pet you can get yet, better than a dog or cat, 
He’s my albuquerque turkey and i’m awfully proud of that 

する必要があります文?

def adjust_linelength(): 
    with open("essay_neb.txt") as file: 
     text = file.read().strip() 
    with open("essay_final.txt", 'w') as file: 
     file.write(textwrap.fill(text, width=60)) 

答えて

0

textwrap documentation for 2.7

textwrap.fill(テキスト[、幅[、...]])

ラップテキスト内の単一の段落によると、単一の文字列を返しますラップされた段落を含む。

テキストを段落に分割してから、各段落でテキストラッパーを実行すると、機能するはずです。

関連する問題