首页 > 解决方案 > 在 django 中将数据保存到 .txt 文件中

问题描述

我正在 Django 中进行一个项目,在该项目中,我只需计算输入句子时的单词数。每次使用该网站时,我都会尝试将字数保存在 .txt 文件中。views.py 是:

from django.http import HttpResponse
from django.shortcuts import render

def homepage(request):
    return render(request,'home.html')

def count(request):
    fulltext = request.GET['fulltext']

    wordlist = fulltext.split()

    f=open('abc.txt','a+')
    f.write('\n')
    f.write(wordlist)
    f.close()

    return render(request,'count.html', {'fulltext':fulltext, 'count':len(wordlist)})

我给出输入句子的主页是:

<h1> Word Count </h1>

<form action = "{% url 'count' %}">
<textarea col='40' rows = '5' name = "fulltext"></textarea>
<br/>
<input type = 'submit' value= 'count!' />
</form>

我显示输出以及字数的页面是:

<h1> hey, there are {{count}} words</h1>
<h1> your text </h1>
{{fulltext}}

该程序在 UI 部分运行良好。当我在主页中给出输入语句并提交时,我在输出页面中得到结果。它还在工作目录中生成一个 abc.txt 文件。但是,那里有部分代码重复,因为在 .txt 文件中我得到了两次相同的输出。也就是说,如果输入句子是“Tom and Jerry”,那么 .txt 文件会存储 3(句子中的单词数)两次而不是一次。有人可以帮忙吗?

标签: pythonhtmldjango

解决方案


推荐阅读