Python:如何在输出文件中的星号框中打印文本?

问题描述 投票:0回答:1

我正在研究以下硬件问题,现在正试图微调我的代码...

编写一个程序,该程序接收带有消息的文件。该消息可以是任何长度。

您的程序将包含两个功能。第一个应该具有处理文件内容的功能。第二个将获取第一个函数的输出,并将消息打印在一个星号框中。

输入文件应该只是单行消息(请参阅随附的输入示例)。输出应采用该消息,将其分为两行,并在框中居中]

这是我当前的代码:

import textwrap

def func1():
    infile=open("october.txt", "r")
    'Pull text from file and assign it to process_contents variable'
    process_contents=infile.read()
    return process_contents


def asterisk_box(width, height):
    'Create a box of asterisks and return it as a string'
    box = '*' * width + '\n'
    for i in range(height - 2):
        box += '*' + ' ' * (width-2) + '*\n'
    box += '*' * width
    return box

def asterisk_message(width, height, message):
    'Put a message within the asterisk box'
    assert len(message) <= height  # Make sure there is room for a message
    assert len(message) <= width  # Make sure the box is wide enough
    box = asterisk_box(25,20)
    box = box.splitlines()
    row = height // 2
    box[row] = "*" + message.center(width) + "*"
    box[row] = textwrap.fill(message,4)
    return '\n'.join(box)


def func2():
    outfile=open("october_output.txt", "w")
    print(asterisk_message(30,25, func1()), file=outfile)
    outfile.close()



func2()


我拥有的代码只能使用一个很小的单词,例如“ hello”;收到任何更多消息,“ assert”将启动,代码将不会运行。有什么方法可以使星号框根据邮件的长度自动扩展或压缩?我试图使用textwrap压缩更长的消息以适合该框,但是这样做使我处于奇怪的格式状态,并且弄乱了星号框,如下所示:


*************************
*                       *
*                       *
*                       *
*                       *
*                       *
*                       *
*                       *
*                       *
*                       *
*                       *
*                       *
so l
et's
try 
long
er?
*                       *
*                       *
*                       *
*                       *
*                       *
*                       *
*************************

python function parameters parameter-passing
1个回答
0
投票
width = 30
message = "This is a test"
msg_ary = message.split(' ')
message1 = ' '.join(msg_ary[0: len(msg_ary) // 2]).center(width, ' ')
message2 = ' '.join(msg_ary[len(msg_ary) // 2:]).center(width, ' ')

print('*' * (width + 4))
print(f'* {message1} *')
print(f'* {message2} *')
print('*' * (width + 4))

> **********************************
> *            This is             *
> *             a test             *
> **********************************

由于这是家庭作业,所以有一些解释:

width = 30:我选择的任意宽度,只要适合您的文本即可。msg_ary = ......:按单词(空格)拆分消息,以使其中断而不拆分单词messag1 = ....,message2 = ....:再次将数组放入句子中,请注意在结尾处方便地调用“ center”:)

© www.soinside.com 2019 - 2024. All rights reserved.