gpt4 book ai didi

python:从文件中读取表(从prettytable创建)并保留空格

转载 作者:行者123 更新时间:2023-12-01 01:13:47 26 4
gpt4 key购买 nike

假设我有以下 file.txt

$ cat file.txt
+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide | 1295 | 1158259 | 600.5 |
| Brisbane | 5905 | 1857594 | 1146.4 |
| Darwin | 112 | 120900 | 1714.7 |
| Hobart | 1357 | 205556 | 619.5 |
| Sydney | 2058 | 4336374 | 1214.8 |
| Melbourne | 1566 | 3806092 | 646.9 |
| Perth | 5386 | 1554769 | 869.4 |
+-----------+------+------------+-----------------+

如果我尝试像这样读取文件:

with open('file.txt') as fp:
lines = fp.readlines()

然后我尝试使用 gtk2.0 文本缓冲区显示每一行(类似于打印):

for eachline in lines:
if idx == 0:
self.textbuffer.delete(start, end)
end = self.textbuffer.get_end_iter()
self.textbuffer.set_text(eachline)
else:
self.textbuffer.insert(end, eachline)
end = self.textbuffer.get_end_iter()

我得到以下输出:

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide | 1295 | 1158259 | 600.5 |
| Brisbane | 5905 | 1857594 | 1146.4 |
| Darwin | 112 | 120900 | 1714.7 |
| Hobart | 1357 | 205556 | 619.5 |
| Sydney | 2058 | 4336374 | 1214.8 |
| Melbourne | 1566 | 3806092 | 646.9 |
| Perth | 5386 | 1554769 | 869.4 |
+-----------+------+------------+-----------------+

有什么建议可以让它看起来更漂亮吗(就像第一个表)?

提前致谢!

最佳答案

您可能希望将字符串格式化为如下所示:

Python: Format output string, right alignment输出中的 with 类似

for align, text in zip('<^>', ['left', 'center', 'right']): 
'{0:{fill}{align}16}'.format(text, fill=align, align=align)

在输出中,您可以指定 with (或根据输入的长度获取它)。

我自己没有使用过 gtk2.0,但也许它会有所帮助 https://docs.python.org/3/library/string.html#formatstrings

关于python:从文件中读取表(从prettytable创建)并保留空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54583322/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com