レポート作成スクリプトを作成しようとしています。簡単に言えば、いくつかの raw_input() を介してユーザーに文字列を送信してもらいます。これらの文字列はグローバル変数に割り当てられます。それらが終了したら、文字列を出力するスクリプトが必要ですが、1 行あたり 80 文字に制限します。私は textwrap モジュールを見て、これを尋ねた他の人を探しました。しかし、生の入力または既存のファイルからスクリプト内で印刷される文字を制限しようとしていて、新しいファイルに印刷しようとしない人々を見つけただけです。基本的に、私がやろうとしていることの短いバージョンであるコードがいくつかあります。
コードは次のとおりです。
def start():
global file_name
file_name = raw_input("\nPlease Specify a filename:\n>>> ")
print "The filename chosen is: %r" % file_name
create_report()
note_type()
def create_report():
global new_report
new_report = open(file_name, 'w')
print "Report created as: %r" % file_name
new_report.write("Rehearsal Report\n")
note_type()
def note_type():
print "\nPlease select which type of note you wish to make."
print """
1. Type1
2. Print
"""
answer = raw_input("\n>>> ")
if answer in "1 1. type1 Type1 TYPE1":
type1_note()
elif answer in "2 2. print Print PRINT":
print_notes()
else:
print "Unacceptable Response"
note_type()
def type1_note():
print "Please Enter your note:"
global t1note_text
t1note_text = raw_input(">>> ")
print "\nNote Added."
note_type()
def print_notes():
new_report.write("\nType 1: %r" % t1note_text)
new_report.close
print "Printed. Goodbye!"
exit(0)
start()
そして、ここに私の端末入力があります
---
new-host-4:ism Bean$ python SO_Question.py
Please Specify a filename:
">>> " test3.txt
The filename chosen is: 'test3.txt'
Report created as: 'test3.txt'
Please select which type of note you wish to make.
1. Type1
2. Print
">>> " 1
Please Enter your note:
">>> "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam at dignissim diam. Donec aliquam consectetur pretium. Sed ac sem eu nulla tincidunt accumsan. Praesent vel velit odio. Donec porta mauris ut eros bibendum consequat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer adipiscing nibh in turpis placerat non interdum magna convallis. Phasellus porta mauris at nibh laoreet ac vulputate elit semper.
Note Added.
Please select which type of note you wish to make.
1. Type1
2. Print
">>> "2
Printed. Goodbye!
new-host-4:ism Bean$
唯一の問題は、ファイル (test3.txt) を開くと、lorem ipsum の段落全体がすべて 1 行に出力されることです。このような:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam at dignissim diam. Donec aliquam consectetur pretium. Sed ac sem eu nulla tincidunt accumsan. Praesent vel velit odio. Donec porta mauris ut eros bibendum consequat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer adipiscing nibh in turpis placerat non interdum magna convallis. Phasellus porta mauris at nibh laoreet ac vulputate elit semper.
textwrap で 1 行あたり 80 文字をファイルに出力するためのアドバイスはありますか?