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



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

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

。这将始终适合其内容。 我知道如何做顶部和底部,但它正在让 ljust 和 rjust 正常工作。 每行可能有一个字符串替换,也可能是 5,这些字符串的 len 可以是 0 到 80 之间的任何值。

我一直在做这样的事情:

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

可是天呐,就是这么乱...这只是一个硬编码的替换。我不知道如何使它动态,比如说第一行有 2 个子,第二行有 3 个子,第三行有 1 个子(所有这些都是列格式)。

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

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

我是这样做的:

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可警惕的对象,然后将其传递到bordered()函数。

你可以

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  |
+-----------------------+

您可以使用 Linux 和 Mac 的 python 标准库中curses模块。您也可以尝试pygcurse适用于Mac,Linux和Windows的库。另外,您可以阅读它。但是对于简单的对话框,您可以使用下一个代码:

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              |
+------------------+
您可以使用

'*'作为字符串格式的宽度和精度字段,如本答案中所述。 下面是一个示例:

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.           |
+-------------------+

我参加聚会迟到了,但这是我的版本:

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 bodyncheers,"
    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               |
+--------------------+

最新更新