在Python单个表格单元格中添加多行

7

我不确定如何绘制下面这样的表格,我尝试使用prettytable但无法在单个单元格中放置多行文本。

NB: 每行文本应基于字符串数量,所以我想每行放置n个字符串。

请问有人可以帮忙吗?

+---- +-------------------+-------------------------------------------------------+
| Id  | Name              | Comment                                               |
+-----+-------------------+-------------------------------------------------------+
| 1   |  Alvina Skiles    | Dolor qui rerum est sed. Sed ipsa repudiandae et      |
|     |                   | Non explicabo voluptas impedit rerum dignissimos.     |
|     |                   | Minima voluptatibus sint voluptates similique.'       |
+-----+-------------------+-------------------------------------------------------+
| 2   |  Chasity Lakin    | Nesciunt ea voluptatem rerum eos rerum ut soluta      |
|     |                   | Animi totam rerum fugiat consectetur odio et          |
|     |                   | repellendus                                           |
+-----+-------------------+-------------------------------------------------------+
| 3   | Miss Brennan Kiehn| Nulla placeat saepe voluptatem molestias dolores ex   |
|     |                   | Reiciendis nostrum adipisci qui enim explicabo.       |
+-----+-------------------+-------------------------------------------------------+

这是我构建表格的数据结构:

[
    {
        "id": "1",
        "name": "Alvina Skiles",
        "comment": 'Dolor qui rerum est sed. Sed ipsa repudiandae et. Non explicabo voluptas impedit rerum dignissimos. Minima voluptatibus
    },
    {
        "id": "2",
        "name" : 'Chasity Lakin',
        "comment": 'Nesciunt ea voluptatem rerum eos rerum ut soluta. Animi totam rerum fugiat consectetur odio et repellendus.',
    },
    {
        "id": "3",
        "name" : 'Miss Brennan Kiehn',
        "comment": 'Nulla placeat saepe voluptatem molestias dolores ex. Reiciendis nostrum adipisci qui enim explicabo.
    },
]

这些选项卡背后的数据是如何表示的? - Scott Hunter
这是一个包含键'id'、'name'和'likes'的字典,当行过长时,我想根据行中字符串的数量将其拆分为多行。 - James Sapam
请更新问题,提供要显示为表格的数据的完整描述。最好提供一个生成示例表格的数据示例。 - Scott Hunter
数据示例与示例表格不匹配。分割注释成几行的标准是什么? - Scott Hunter
我想按行中字符串的数量进行拆分,例如每10个字符串我想要拆分。 - James Sapam
2个回答

7

看起来prettytable可以很好地处理换行,因此一个快速的格式化函数可能只需要这个技巧。这是我的示例:

import prettytable
from prettytable import ALL as ALL
items_table = prettytable.PrettyTable(hrules=ALL)
items_table.field_names = ["id", "name", "comment"]

items = [
    {
        "id": "1",
        "name": "Alvina Skiles",
        "comment": 'Dolor qui rerum est sed. Sed ipsa repudiandae et. Non explicabo voluptas impedit rerum dignissimos. Minima voluptatibus'
    },
    {
        "id": "2",
        "name" : 'Chasity Lakin',
        "comment": 'Nesciunt ea voluptatem rerum eos rerum ut soluta. Animi totam rerum fugiat consectetur odio et repellendus.'
    },
    {
        "id": "3",
        "name" : 'Miss Brennan Kiehn',
        "comment": 'Nulla placeat saepe voluptatem molestias dolores ex. Reiciendis nostrum adipisci qui enim explicabo.'
    },
]

def format_comment(comment, max_line_length):
    #accumulated line length
    ACC_length = 0
    words = comment.split(" ")
    formatted_comment = ""
    for word in words:
        #if ACC_length + len(word) and a space is <= max_line_length 
        if ACC_length + (len(word) + 1) <= max_line_length:
            #append the word and a space
            formatted_comment = formatted_comment + word + " "
            #length = length + length of word + length of space
            ACC_length = ACC_length + len(word) + 1
        else:
            #append a line break, then the word and a space
            formatted_comment = formatted_comment + "\n" + word + " "
            #reset counter of length to the length of a word and a space
            ACC_length = len(word) + 1
    return formatted_comment

for item in items:
    item["comment"] = format_comment(item["comment"], 42)
    items_table.add_row([item["id"], item["name"], item["comment"]])

print(items_table)

下面是输出结果:

+----+--------------------+--------------------------------------------+
| id |        name        |                  comment                   |
+----+--------------------+--------------------------------------------+
| 1  |   Alvina Skiles    |     Dolor qui rerum est sed. Sed ipsa      |
|    |                    |  repudiandae et. Non explicabo voluptas    |
|    |                    |     impedit rerum dignissimos. Minima      |
|    |                    |               voluptatibus                 |
+----+--------------------+--------------------------------------------+
| 2  |   Chasity Lakin    | Nesciunt ea voluptatem rerum eos rerum ut  |
|    |                    |     soluta. Animi totam rerum fugiat       |
|    |                    |     consectetur odio et repellendus.       |
+----+--------------------+--------------------------------------------+
| 3  | Miss Brennan Kiehn | Nulla placeat saepe voluptatem molestias   |
|    |                    |  dolores ex. Reiciendis nostrum adipisci   |
|    |                    |            qui enim explicabo.             |
+----+--------------------+--------------------------------------------+

6

我今天只需要同样的东西,看了不同的解决方案后,我创建了这个:

from prettytable import PrettyTable
from textwrap import fill

header = ["Id", "Name", "Comment"]
table = PrettyTable(field_names=header, align='l')

items = [
    {
        "id": "1",
        "name": "Alvina Skiles",
        "comment": 'Dolor qui rerum est sed. Sed ipsa repudiandae et. Non explicabo voluptas impedit rerum dignissimos. Minima voluptatibus'
    },
    {
        "id": "2",
        "name" : 'Chasity Lakin',
        "comment": 'Nesciunt ea voluptatem rerum eos rerum ut soluta. Animi totam rerum fugiat consectetur odio et repellendus.'
    },
    {
        "id": "3",
        "name" : 'Miss Brennan Kiehn',
        "comment": 'Nulla placeat saepe voluptatem molestias dolores ex. Reiciendis nostrum adipisci qui enim explicabo.'
    },
]


for item in items:
    table.add_row([item["id"], item["name"], fill(item["comment"], width=50)])
    # you can change the width="number" to as many character you want per line.

print(table)

因此,结果就像这样:
+----+--------------------+---------------------------------------------------+
| Id | Name               | Comment                                           |
+----+--------------------+---------------------------------------------------+
| 1  | Alvina Skiles      | Dolor qui rerum est sed. Sed ipsa repudiandae et. |
|    |                    | Non explicabo voluptas impedit rerum dignissimos. |
|    |                    | Minima voluptatibus                               |
| 2  | Chasity Lakin      | Nesciunt ea voluptatem rerum eos rerum ut soluta. |
|    |                    | Animi totam rerum fugiat consectetur odio et      |
|    |                    | repellendus.                                      |
| 3  | Miss Brennan Kiehn | Nulla placeat saepe voluptatem molestias dolores  |
|    |                    | ex. Reiciendis nostrum adipisci qui enim          |
|    |                    | explicabo.                                        |
+----+--------------------+---------------------------------------------------+

就这样,只需使用文本包装(Python内置)和PrettyTable。


使用 prettyTable.add_row([item[row], width = 50]) 会出现语法错误。 - aJazz
你好@aJazz,实际上参数“width=50”并不是针对“add_row”方法的,而是一个文本包装(textwrap.fill)的参数。看一下代码,特别关注括号。我在这边重新运行了整个代码,它仍然非常正常地工作着。 - Rafael Magalhães
哦,我不知道有textwrap包,@RafaelMagalhães,我喜欢你的解决方案! - rolandog

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接