Python - 创建动态大小的文本边框

时间:2013-12-24 07:11:32

标签: python command-line border

我正在创建一个命令行脚本,我希望有一个框...

+--------+
|        |
|        |
|        |
+--------+

......总是符合其内容。我知道如何做到顶部和底部,但它正在使ljust和rjust正常工作。每行可能有一个字符串替换,或5,并且这些字符串的len可以是介于0和80之间的任何字符串。

我一直在做这样的事情:

print "|%s|" % (my_string.ljust(80-len(my_string)))

但是,神圣的dang是那么混乱......而这只是一个硬编码的替代品。我不知道如何让它变得动态,比如说第一行的2个子站点,第二行的3个子站点和第3行的1个子站点(所有这些都是列格式)。

所以对于一个基本的例子,我需要:

+--------+
| 1      |
| 1 2 3  |
| 1 2    |
+--------+

5 个答案:

答案 0 :(得分:4)

我这样做:

def bordered(text):
    lines = text.splitlines()
    width = max(len(s) for s in lines)
    res = ['┌' + '─' * width + '┐']
    for s in lines:
        res.append('│' + (s + ' ' * width)[:width] + '│')
    res.append('└' + '─' * width + '┘')
    return '\n'.join(res)

因此,您首先将所有对象格式化为text wariable,然后将其传递给bordered()函数。

答案 1 :(得分:1)

您可以使用python标准库中的curses模块用于Linux和Mac。您也可以在Mac,Linux和Windows上试用pygcurse库。 此外,您可以read it。 但是对于简单的对话框,您可以使用下一个代码:

def my_text_frame(string_lst, width=20):
    g_line = "+{0}+".format("-"*(width-2))
    print g_line
    for line in string_lst:
        print "| {0:<{1}} |".format(line, width-4)
    print g_line
my_text_frame("""Some text
123456 789
123""".splitlines())

输出:

+------------------+
| Some text        |
| 123456 789       |
| 123              |
+------------------+

答案 2 :(得分:1)

您可以将'*'用于字符串格式的宽度和精度字段,如this answer中所述。这是一个示例:

text = """\
This is
a test of the
column formatting
system.""".splitlines()

maxlen = max(len(s) for s in text)
colwidth = maxlen + 2

print '+' + '-'*colwidth + '+'
for s in text:
    print '| %-*.*s |' % (maxlen, maxlen, s)
print '+' + '-'*colwidth + '+'

打印:

+-------------------+
| This is           |
| a test of the     |
| column formatting |
| system.           |
+-------------------+

答案 3 :(得分:1)

我来晚了,但这是我的版本:

def breakLine(text, wrap=80):
    if len(text) > wrap:
        char = wrap
        while char > 0 and text[char] != ' ':
            char -= 1
        if char:
            text = [text[:char]] + breakLine(text[char + 1:], wrap)
        else:
            text = [text[:wrap - 1] + '-'] + breakLine(text[wrap - 1:], wrap)
        return text
    else:
        return [cleanLine(text)]

def cleanLine(text):
    if text[-1] == ' ':
        text = text[:-1]
    if text[0] == ' ':
        text = text[1:]
    return text

def boxPrint(text, wrap=0):
    line_style = '-'
    paragraph = text.split('\n')
    if wrap>0:
        index = 0
        while index < len(paragraph):
            paragraph[index] = cleanLine(paragraph[index])
            if len(paragraph[index]) > wrap:
                paragraph = paragraph[:index] + breakLine(paragraph[index]\
                    , wrap) + paragraph[index + 1:]
            index += 1

    length = (max([len(line) for line in paragraph]))
    print '+' + line_style * length + '+'
    for line in paragraph:
        print '|' + line + ' ' * (length - len(line)) + '|'
    print '+' + line_style * length + '+'

if __name__ == "__main__":
    text = "Some text comes here to be printed in a box!!!"
    boxPrint(text, 20)
    text = "Title:\nBody lorem ipsum something body\ncheers,"
    boxPrint(text, 20)
    boxPrint(text)
    text = "No Space:\nThisIsATextThatHasNoSpaceForWrappingWhichGetsBrokenUsingDashes"
    boxPrint(text, 20)

打印哪些:

+--------------------+
|Some text comes here|
|to be printed in a  |
|box!!!              |
+--------------------+
+----------------+
|Title:          |
|Body lorem ipsum|
|something body  |
|cheers,         |
+----------------+
+-------------------------------+
|Title:                         |
|Body lorem ipsum something body|
|cheers,                        |
+-------------------------------+
+--------------------+
|No Space:           |
|ThisIsATextThatHasN-|
|oSpaceForWrappingWh-|
|ichGetsBrokenUsingD-|
|ashes               |
+--------------------+

答案 4 :(得分:0)

您可以使用tabulate

执行此操作
from tabulate import tabulate

text = """
some words that
could be dynamic but 
are currently static
"""

table = [[text]]
output = tabulate(table, tablefmt='grid')

print(output)

输出:

+-----------------------+
| some words that       |
| could be dynamic but  |
| are currently static  |
+-----------------------+