首页 > 解决方案 > 从 sqlite 为 pandas 数据框添加字幕并使用 Python 使用 Web 浏览器输出

问题描述

我的 Python 脚本中有一个函数,它从 sqlite 数据库中选择值到 Pandas (pd) 数据框中,然后在 Web 浏览器中输出。

我希望输出的表格在浏览器中显示表格的标题。

标题应该看起来像

“此表显示了年 year.get() 月份的收款率” year.get()

我的功能代码:

def all_collectors_info():
      Database()
      a = cursor.execute("SELECT * FROM `collectors` WHERE Month = ? AND Year = ?", (MONTH.get(), YEAR.get(),))
      fetch = cursor.fetchall()
      z = [x for x in fetch]
      cols = [column[0] for column in a.description]
      pd.set_option('display.max_columns', None)
      pd.set_option('display.max_rows', None)
      df= pd.DataFrame.from_records(data = fetch, columns = cols, index = list(range(1, (len(z)+1))))

      html = df.to_html()
      text_file = open("index.html", "w")
      text_file.write(html)
      text_file.close()

标签: pythonhtmlpandassqlite

解决方案


没有直接选项可以将<caption>标签从熊猫添加到表中,但您可以像这样附加标题(<h#> 标签)

heading_template = '<h3>This table shows the rate of collections for the month of {month} in the year {year}</h3>\n'
html = df.to_html()
html = heading_template.format(month=MONTH.get(), year=YEAR.get()) + html

所以你的最终功能是

def all_collectors_info():
      Database()
      a = cursor.execute("SELECT * FROM `collectors` WHERE Month = ? AND Year = ?", (MONTH.get(), YEAR.get(),))
      fetch = cursor.fetchall()
      z = [x for x in fetch]
      cols = [column[0] for column in a.description]
      pd.set_option('display.max_columns', None)
      pd.set_option('display.max_rows', None)
      df= pd.DataFrame.from_records(data = fetch, columns = cols, index = list(range(1, (len(z)+1))))

      heading_template = '<h3>This table shows the rate of collections for the month of {month} in the year {year}</h3>\n'
      html = df.to_html()
      html = heading_template.format(month=MONTH.get(), year=YEAR.get()) + html
      text_file = open("index.html", "w")
      text_file.write(html)
      text_file.close()

推荐阅读