0

我正在尝试编写报告创建脚本。简单地说,我让用户通过几个 raw_input()s 提交字符串。这些字符串被分配给全局变量,当它们完成后,我需要脚本来打印字符串,但将其限制为每行仅 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 的整个段落都打印到一行。像这样:

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 每行打印 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 回答
1

在 python 3 中,您可以使用textwrap.fill打印 80 个字符行:

import textwrap

print (textwrap.fill(your_text, width=80))

https://docs.python.org/3.6/library/textwrap.html

于 2018-01-12T09:59:12.747 回答
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 回答