在 python 中将列表转换为 HTML 表的最简单方法?

发布于 2024-08-05 23:12:36 字数 542 浏览 4 评论 0原文

假设我有一个像这样的列表:

['one','two','three','four','five','six','seven','eight','nine']

我想尝试将这些数据转换为各种尺寸的 HTML 表:

one     two    three
four    five   six
seven   eight  nine

或者

one    four   seven
two    five   eight
three  six    nine

或者

one    two   three  four
five   six   seven  eight
nine

是否有一个库可以处理这个问题,而不需要进行疯狂的列表拼接或嵌套 for 循环?我的谷歌搜索显示有一些 HTML 库,但我没有时间逐一浏览每个库,看看它们是否可以很好地处理表格。有人曾经不得不这样做吗?如果是的话你是怎么做到的?

lets say I have a list like so:

['one','two','three','four','five','six','seven','eight','nine']

and I want to experiment with turning this data into a HTML table of various dimensions:

one     two    three
four    five   six
seven   eight  nine

or

one    four   seven
two    five   eight
three  six    nine

or

one    two   three  four
five   six   seven  eight
nine

Is there a library that can handle this without needing to do crazy list splicing or nested for loops? My google searches reveal that there are a few HTML libraries, but I don't have the time to go through each one to see if they can handle tables very well. Has anyone ever had to do this? If so how did you do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

面如桃花 2024-08-12 23:12:36

使用 tabulate

from tabulate import tabulate

table = [['one','two','three'],['four','five','six'],['seven','eight','nine']]

print(tabulate(table, tablefmt='html'))

会产生以下输出。

<table>
<tbody>
<tr><td>one  </td><td>two  </td><td>three</td></tr>
<tr><td>four </td><td>five </td><td>six  </td></tr>
<tr><td>seven</td><td>eight</td><td>nine </td></tr>
</tbody>
</table>

Use tabulate

from tabulate import tabulate

table = [['one','two','three'],['four','five','six'],['seven','eight','nine']]

print(tabulate(table, tablefmt='html'))

Which produces the following output.

<table>
<tbody>
<tr><td>one  </td><td>two  </td><td>three</td></tr>
<tr><td>four </td><td>five </td><td>six  </td></tr>
<tr><td>seven</td><td>eight</td><td>nine </td></tr>
</tbody>
</table>
对风讲故事 2024-08-12 23:12:36

我会将您的问题分解为两部分:

  • 给定一个“平面列表”,生成一个子列表列表,其中子列表具有给定的长度,并且整个列表可以按“行主要”顺序排列(您的第一个和第三个示例)或“栏目专业”(你的第二个例子);
  • 给定一个包含字符串项的子列表列表,从中生成一个 HTML 表。

我认为这两个任务确实非常不同,将它们混在一起没有什么好处(也不会失去很多),所以如果有任何设计良好的库做了这样的混在一起,我会感到惊讶。

对于第 1 点,行优先很容易:

def row_major(alist, sublen):      
  return [alist[i:i+sublen] for i in range(0, len(alist), sublen)]

而列优先也没有那么糟糕:

def col_major(alist, sublen):
  numrows = (len(alist)+sublen-1) // sublen 
  return [alist[i::sublen] for i in range(numrows)]

例如...:

L = ['one','two','three','four','five','six','seven','eight','nine']
for r in row_major(L, 3): print r
print
for r in col_major(L, 3): print r
for r in row_major(L, 4): print r

产生您想要的三个结果(每行一个列表,还不是 HTML 形式;-)。

问题的后半部分——从字符串列表中生成一个 HTML 表:

def html_table(lol):
  print '<table>'
  for sublist in lol:
    print '  <tr><td>'
    print '    </td><td>'.join(sublist)
    print '  </td></tr>'
  print '</table>'

如果您想将其作为单个字符串获取而不是打印出来,请将每个 print 更改为 yield 并使用 '\n'.join(html_table(lol))

现在您有了两个简单、有用、可用且可重用的构建块——每当您想要将数据呈现为除 HTML 表格之外的任何内容时,以及每当列表列表呈现为 HTML 时,将它们分开会派上用场。 table 来自任何其他构建它的方式。在应用程序代码中将它们放在一起很容易,但当然,执行简单的“粘合例程”也很容易,例如,假设基于 yieldhtml_table 并且需要单个字符串结果:

def list_to_html_table(alist, sublength, column_major=False):
  if column_major:
    lol = col_major(alist, sublength)
  else:
    lol = row_major(alist, sublength)
  return ''.join(html_table(lol))

这种构建块方法不是真的比用大团糊状胶水进行编程更好、更令人愉快并且更有效率吗...?-)

I would decompose your problem into two parts:

  • given a "flat list", produce a list of sublists where the sublists are of a given length and the overall list may be walked into either a "row major" order (your first and third example) or "column major" (your second example);
  • given a list of sublists with string items, produce an HTML table out of it.

I think the two tasks are really very distinct and there's nothing to gain (and much to lose) in mushing them up, so I would be astonished if any well-designed library did such mushing.

For point 1, row-major is easy:

def row_major(alist, sublen):      
  return [alist[i:i+sublen] for i in range(0, len(alist), sublen)]

and column-major not that bad:

def col_major(alist, sublen):
  numrows = (len(alist)+sublen-1) // sublen 
  return [alist[i::sublen] for i in range(numrows)]

for example...:

L = ['one','two','three','four','five','six','seven','eight','nine']
for r in row_major(L, 3): print r
print
for r in col_major(L, 3): print r
for r in row_major(L, 4): print r

produces your three desired results (one list per row, not in HTML form yet;-).

The second half of the problem -- produce an HTML table from a list of lists of strings:

def html_table(lol):
  print '<table>'
  for sublist in lol:
    print '  <tr><td>'
    print '    </td><td>'.join(sublist)
    print '  </td></tr>'
  print '</table>'

If you want to get it as a single string rather than print it out, change each print into yield and use '\n'.join(html_table(lol)).

Now you have two simple, useful, usable and reusable building blocks -- having them separate will come in handy whenever you want to present your data as anything BUT an HTML table, and also whenever the list-of-lists to present as an HTML table comes from any other way of building it. Putting them together is easy to do in your application code, but of course it's also easy to do a simple "glue routine", e.g., assuming the yield-based version of html_table and that a single string result is desired:

def list_to_html_table(alist, sublength, column_major=False):
  if column_major:
    lol = col_major(alist, sublength)
  else:
    lol = row_major(alist, sublength)
  return ''.join(html_table(lol))

Isn't this building-blocks approach really nicer and more pleasant, as well as more productive, than programming in terms of big blobs of mushed-up glue...?-)

满身野味 2024-08-12 23:12:36

为了便于将来参考,我实现了一个名为 simpletable 的小型 Python 模块,以提供简单的 HTML 表格生成功能。它还涉及这个问题中描述的问题。

使用方法如下简单:

import simpletable

test_data = [str(x) for x in range(20)]
formatted_data = simpletable.fit_data_to_columns(test_data, 5)
table = simpletable.SimpleTable(formatted_data)
html_page = simpletable.HTMLPage(table)
html_page.save("test_page.html")

由于不需要第三方包,您可以从我的存储库获取代码 并在您的项目中使用它。

Just for future reference, I implemented a small Python module called simpletable to provide easy HTML table generation. It also that deals with the issue described in this question.

The usage is as simple as below:

import simpletable

test_data = [str(x) for x in range(20)]
formatted_data = simpletable.fit_data_to_columns(test_data, 5)
table = simpletable.SimpleTable(formatted_data)
html_page = simpletable.HTMLPage(table)
html_page.save("test_page.html")

Since it does not require third-party packages, you can just get the code from my repository and use it in your projects.

咆哮 2024-08-12 23:12:36

另一种选择是prettytable:

from prettytable import PrettyTable
pt = PrettyTable()

如果要生成html格式:

print(pt.get_html_string())

如果只生成ascii格式表:

print(pt.get_string())

请参考官方文档:https://ptable.readthedocs.io/en/latest/tutorial.html 了解更多选项,例如启用不同类型的样式。

享受。

another choice is prettytable:

from prettytable import PrettyTable
pt = PrettyTable()

if you want to generate html format:

print(pt.get_html_string())

if only generate ascii format table:

print(pt.get_string())

pls refer to the official document: https://ptable.readthedocs.io/en/latest/tutorial.html for more option, eg enable different kinds of style.

enjoy.

小姐丶请自重 2024-08-12 23:12:36

嗯,周围有几个模板库(Genshi 是我喜欢的一个,但还有很多其他的)。

或者你可以这样做:

def print_table(data, row_length):
    print '<table>'
    counter = 0
    for element in data:
        if counter % row_length == 0:
            print '<tr>'
        print '<td>%s</td>' % element
        counter += 1
        if counter % row_length == 0:
            print '</tr>'
    if counter % row_length != 0:
        for i in range(0, row_length - counter % row_length):
            print '<td> </td>'
        print '</tr>'
    print '</table>'

Well there are several templating libraries around (Genshi is one I like but there are many others).

Alternatively you could do something like:

def print_table(data, row_length):
    print '<table>'
    counter = 0
    for element in data:
        if counter % row_length == 0:
            print '<tr>'
        print '<td>%s</td>' % element
        counter += 1
        if counter % row_length == 0:
            print '</tr>'
    if counter % row_length != 0:
        for i in range(0, row_length - counter % row_length):
            print '<td> </td>'
        print '</tr>'
    print '</table>'
£烟消云散 2024-08-12 23:12:36

也许操作模板对于玩具代码来说更容易,=p

def get_html_tbl(seq, col_count):
    if len(seq) % col_count:
        seq.extend([''] * (col_count - len(seq) % col_count))
    tbl_template = '<table>%s</table>' % ('<tr>%s</tr>' % ('<td>%s</td>' * col_count) * (len(seq)/col_count))
    return tbl_template % tuple(seq)

Maybe manipulate template is easier for toy codes, =p

def get_html_tbl(seq, col_count):
    if len(seq) % col_count:
        seq.extend([''] * (col_count - len(seq) % col_count))
    tbl_template = '<table>%s</table>' % ('<tr>%s</tr>' % ('<td>%s</td>' * col_count) * (len(seq)/col_count))
    return tbl_template % tuple(seq)
那些过往 2024-08-12 23:12:36

尽管之前已经回答过这个问题,但这里是使用 numpypandas DataFrame 的另一种解决方案。由于现在很多人对数据科学感兴趣,我认为使用 pandas 解决这个问题会很有趣:

GITHUB 解决方案:
我已在 我的 GitHub 存储库,您也可以在 Google Colaboratory 中运行和探索(我强烈推荐这样做)。< /p>

我在这里使用的自定义函数 (generate_html_with_table())可以在这个Jupyter Notebook

解决方案:
要获得您的解决方案,请运行以下命令:

data = ['one','two','three','four','five','six','seven','eight','nine']
columns = 4                   # Number of Columns
columns_or_rows = columns
column_name_prefix = 'Column' # Prefix for Column headers
span_axis = 1                 # Span along a row (1) or a column (0) first
showOutput = True             # Use False to suppress printing output

# Generate HTML
data_html, data_df = generate_html_with_table(data, columns_or_rows, column_name_prefix, span_axis, showOutput)

输出:

HTML Generated: 

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Column_0</th>
      <th>Column_1</th>
      <th>Column_2</th>
      <th>Column_3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>one</td>
      <td>two</td>
      <td>three</td>
      <td>four</td>
    </tr>
    <tr>
      <th>1</th>
      <td>five</td>
      <td>six</td>
      <td>seven</td>
      <td>eight</td>
    </tr>
    <tr>
      <th>2</th>
      <td>nine</td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>

code_output_with_spanning_along_a_row

Although this has been answered before, here is another solution by using numpy and pandas DataFrame. Since a lot of people are interested in data-science nowadays, I thought solving this using pandas would be fun:

GITHUB SOLUTION:
I have made my solution available at my GitHub Repository which you can also run and explore in Google Colaboratory (I strongly recommend this).

The custom function (generate_html_with_table()) that I used here is available in this Jupyter Notebook.

SOLUTION:
To get your solution run the following:

data = ['one','two','three','four','five','six','seven','eight','nine']
columns = 4                   # Number of Columns
columns_or_rows = columns
column_name_prefix = 'Column' # Prefix for Column headers
span_axis = 1                 # Span along a row (1) or a column (0) first
showOutput = True             # Use False to suppress printing output

# Generate HTML
data_html, data_df = generate_html_with_table(data, columns_or_rows, column_name_prefix, span_axis, showOutput)

OUTPUT:

HTML Generated: 

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>Column_0</th>
      <th>Column_1</th>
      <th>Column_2</th>
      <th>Column_3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>one</td>
      <td>two</td>
      <td>three</td>
      <td>four</td>
    </tr>
    <tr>
      <th>1</th>
      <td>five</td>
      <td>six</td>
      <td>seven</td>
      <td>eight</td>
    </tr>
    <tr>
      <th>2</th>
      <td>nine</td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>

code_output_with_spanning_along_a_row

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文