[英]Displaying data from a txt file in a html element using Flask
在文本文件“ incorrect_answers.txt”中提交表單后,我目前有一個文本文件,其中記錄了“ {level number},{name},{answer} ” ,如下所示:
1, bob, answerone
1, nicky, answertwo
1, laura, answerthree
使用Python和Flask,我的目標是在HTML頁面上的表格中顯示數據,如下所示:
| Level | Name | Answer |
| 1 | bob | answerone |
| 2 | nicky | answertwo |
| 3 | laura | answerthree |
目前,我正在通過以下函數調用文本文件中的數據:
def get_incorrect_answers():
with open("data/incorrect_answers.txt", "r") as file:
incorrect_answers = file.readlines()
return incorrect_answers
該功能的結果當然是:
['1, bob, answerone\n', '1, nicky, answertwo\n', '1, laura, answerthree\n']
請有人能解釋處理此輸出的最佳方法,以便使我得到一個以HTML顯示的表格,類似於上面顯示的內容嗎?
我無法訪問列表中字符串中的值
由於文本文件具有逗號分隔的值,請嘗試
import pandas as pd
data = pd.read_csv('path to textfile', sep=',', header=None)
data.to_html()
將數據傳遞到模板渲染器,然后通過循環在模板中渲染它,說這是名為mytable.html的模板
<table>
<thead>
<tr>
{% for subfield in column_names %}
<th>{{ subfield }}</th>
{% endfor %}
</tr>
{% for item in incorrect_answers %}
<tr>
{% for subitem in item %}
<td> {{ subitem }}</td>
</tr>
</thead>
然后用類似的東西渲染它
@app.route('/incorrect_answers')
def get_incorrect_answers():
with open("data/incorrect_answers.txt", "r") as file:
incorrect_answers = file.readlines()
return render_template('mytable.html', column_names=['Level', 'Name', 'Answer'],
incorrect_answers=incorrect_answers)
當您轉到http:// localhost:port / incorrect_answers時 ,將看到您的模板出現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.