我是Flask的新手,我想构建一个简单的Web应用程序。现在看起来像这样:
您在文本框中输入一些文本,然后单击提交。当您单击提交时,结果如下:(假设我输入的句子是“这是测试”)
因此,它显示了一些结果(正/负),并且还可以选择将句子添加到数据集(平面文件)中,并带有标签(正或负,这就是为什么有2个按钮的原因)
问题:我正在努力将第一步中文本框中的输入文本(变量input_text
)传递给需要输入文本的正/负按钮将其添加到平面文件中。
这是我到目前为止的代码。
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
@app.route('/process-data', methods=['GET', 'POST'])
def process_data():
if request.method == 'GET':
return render_template('index.html')
if request.method == 'POST':
# if submit button is clicked
if request.form['submit'] == 'Submit':
# get the text from the form that was filled in
input_text = request.form['text']
# final result shown on the screen, hardcoded in this case because out of scope for my question
final_result = "negative"
if request.form['submit'] == 'Positive':
f = open('dataset/dataset.tsv', 'a')
f.write(input_text + '\t' + 'positive')
# if negative button is clicked
if request.form['submit'] == 'Negative':
f = open('dataset/dataset.tsv', 'a')
f.write(input_text + '\t' + 'negative')
# show the result on the page
return render_template('index.html', result=final_result, text=input_text)
<!doctype html>
<head>
<title>Sentiment Analysis</title>
<link rel="stylesheet" media="screen" href ="static/bootstrap.min.css">
<link rel="stylesheet" href="static/bootstrap-theme.min.css">
<meta name="viewport" content = "width=device-width, initial-scale=1.0">
</head>
<br/>
<div class="container">
<form action="/process-data" method="post" role="form">
<div class="form-group">
<label for="text">Text:</label>
<input type="text" class="form-control" name="text" placeholder="Input sentence here">
</div>
<input type="submit" name="submit" value="Submit" class="btn btn-success">
</form>
<br/>
{% if result == 'positive' %}
<div class="alert alert-success">
Prediction from all models using majority vote: <strong>{{ result }}</strong>
</div>
{% elif result == 'negative' %}
<div class="alert alert-danger">
Prediction from all models using majority vote: <strong>{{ result }}</strong>
</div>
{% elif result == 'unknown' %}
<div class="alert alert-warning">
Prediction from all models using majority vote: <strong>{{ result }}</strong>
</div>
{% endif %}
{% if result == 'positive' or result == 'negative' or result == 'unknown' %}
<h2>Add to dataset</h2>
<form action="/process-data" method="post" role="form">
<div class="form-group">
<label for="add-dataset">Sentence:</label>
{{ text }}
<br/><label for "label">Label:</label>
<input type="submit" name="submit" value="Positive" class="btn btn-success">
<input type="submit" name="submit" value="Negative" class="btn btn-danger">
</div>
</form>
{% endif %}
</div>
</html>