python - 在 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(句子中的单词数)两次而不是一次。有人可以帮忙吗?
解决方案
推荐阅读
- javascript - Scale of chart generated by using dc.js is returning NaN
- python - 使用 Tesseract 从图像中识别时间
- python - python: using ctypes.windll.kernel32.GetTickCount64 to get uptime gives negative result
- google-sheets - Copy row from table if value in table meets condition
- stored-procedures - Snowflake Stored Procedure Throws JavaScript Error
- c# - 检查一个 int 属性是否具有来自 HTTP 请求的分配值
- php - 无法添加或更新子行:外键约束失败 - 但我可以看到该值确实存在
- python - 在python中解析具有多个同名子级的xml子级
- mqtt - Apache ActiveMQ Artemis MQTT 代理拒绝连接 - 可能的连接限制
- web-scraping - 网页抓取 , 云存储