2017-02-21 57 views
1

我試圖編寫一個輸出文件,將每行字符限制爲60個字符。我設法讀取文本文件並使其每行有60個字符,但是它添加了werent假定在同一行上的文字。例如,在文件中讀取是如何在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(文本[,寬度[,...]])

裹在文本的一個段落,並返回一個字符串包含包裝的段落。

如果您先將文本分成段落,然後在每個段落上運行textwrapper,它應該可以工作。