gpt4 book ai didi

python - 如何在 Django 网页的表格中显示我的 python 代码?

转载 作者:行者123 更新时间:2023-11-30 22:11:50 25 4
gpt4 key购买 nike

我用Python编写了一些代码,它读取两个字符串,删除标点符号,然后在矩阵表中比较它们中的单词,并将其打印到控制台。

如何转换代码以在 Django 框架中使用。我想在网络上显示类似的矩阵。我已经将它导入到 View 中了。请有人指出我正确的方向吗?我一直在使用 django 项目和 lynda 来学习,

编辑:

感谢各位的帮助。设法让它显示在网页上。但它会将所有内容作为单个字符串打印出来。如何设计得更好一点?

originalpythoncode djangowebpage

最佳答案

将数据传递到“Django 网页”就像将值的字典从 Django View 传递到 Django 模板一样。

什么是 Django 模板?Django 模板是 Django 的“MTV”设计模式中的“T”。在传统的 MVC 设计模式(模型- View - Controller )中, View 是显示内容的地方。在 Django 中,模板是显示内容的地方。奇怪的是,Django 中的“ View ”实际上是 Controller 。我花了一段时间才明白过来。

为什么我们使用类似字典的上下文?通过将键映射到值,我们在 Django 模板中实现了超快速的 [O(1)/constant] 查找。

考虑到所有这些,我建议使用“TemplateView”通用 View ,在 utils 文件中完成工作,将 utils 导入 View ,然后通过上下文字典将数据传递到模板。所以它看起来像这样:

local_utils.py
import string
import pandas as pd
pd.set_option('display.max_columns', None)

def generate_out_matrix():

with open('./arrayattempts/samp.txt', 'r') as file1:
sampInput=file1.read().replace('\n', '')
#print(sampInput)

with open('./arrayattempts/ref.txt', 'r') as file2:
refInput=file2.read().replace('\n', '')
#print(refInput)

sampArray = [word.strip(string.punctuation) for word in sampInput.split()]
refArray = [word.strip(string.punctuation) for word in refInput.split()]

out=pd.DataFrame(index=refArray,columns=sampArray)

for i in range(0, out.shape[0]):
for word in sampArray:
out.ix[i,str(word)] = out.index[i].count(str(word))

return out.as_matrix()

views.py
from appname.local_utils import generate_out_matrix
class Detail(TemplateView):
template_name = 'appname/yourhtml.html'

# Will render on each call to URL for 'Detail'
def get_context_data(self):
out = generate_out_matrix()
context['out'] = out
return context

应用程序名称/templates/yourhtml.html

{% if out %}
{% for row in out_matrix %}
{% for o in row %}
{{ o }}
{% endfor %}
<br>
{% endfor %}
{% endif %}

urls.py
path('/your_path', views.Detail.as_view()),

https://docs.djangoproject.com/en/2.0/ref/templates/api/#rendering-a-context

关于python - 如何在 Django 网页的表格中显示我的 python 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51304566/

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