0

レポート作成スクリプトを作成しようとしています。簡単に言えば、いくつかの 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 文字をファイルに出力するためのアドバイスはありますか?

4

3 に答える 3

2

追加のモジュールを使用したくない場合は、ユーザー入力の値を自分で 80 文字のチャンクに分割できます。

def split_input(string, chunk_size):
    num_chunks = len(string)/chunk_size
    if (len(string) % chunk_size != 0):
        num_chunks += 1
    output = []
    for i in range(0, num_chunks):
        output.append(string[chunk_size*i:chunk_size*(i+1)])
    return output

次に、出力リストをファイルに出力できます。

input_chunks = split_input(user_input, 80)
for chunk in input_chunk:
    outFile.write(chunk + "\n")

アップデート:

このバージョンでは、スペースで区切られた単語が尊重されます。

def split_input(user_string, chunk_size):
    output = []
    words = user_string.split(" ")
    total_length = 0

    while (total_length < len(user_string) and len(words) > 0):
        line = []
        next_word = words[0]
        line_len = len(next_word) + 1

        while  (line_len < chunk_size) and len(words) > 0:
            words.pop(0)
            line.append(next_word)

            if (len(words) > 0):
                next_word = words[0]
                line_len += len(next_word) + 1

        line = " ".join(line)
        output.append(line)
        total_length += len(line) 

    return output
于 2013-03-27T19:19:39.477 に答える
0

Textwrapモジュールを試して使用できます。

from textwrap import TextWrapper

def print_notes(t1note_text):
    wrapper = TextWrapper(width=80)
    splittext = "\n".join(wrapper.wrap(t1note_text))
    new_report.write("\nType 1: %r" % splittext)
    new_report.close
    print "Printed. Goodbye!"
    exit(0)
于 2013-03-27T18:59:51.450 に答える