如何使用django在html中运行python脚本并从html输入表单获取变量

时间:2017-11-01 06:29:13

标签: python html django

我有一个情感分析python脚本,但我想让它在html中运行并从html页面获取输入表单,并在html页面中显示结果。 我已经使用django框架来运行html页面。但是我不知道如何将它与我的python脚本连接起来。

这是我的python脚本

query = input("query? \n")
number = input("number of tweets? \n")

results = api.search(
   lang="en",
   q=query + " -rt",
   count=number,
   result_type="recent"
)

print("--- Gathered Tweets \n")

## open a csv file to store the Tweets and their sentiment
file_name = 'Sentiment_Analysis_of_{}_Tweets_About_{}.csv'.format(number, query)

with open(file_name, 'w', newline='') as csvfile:
    csv_writer = csv.DictWriter(
        f=csvfile,
        fieldnames=["Tweet", "Sentiment"]
    )
csv_writer.writeheader()

print("--- Opened a CSV file to store the results of your sentiment analysis... \n")

## tidy up the Tweets and send each to the AYLIEN Text API
   for c, result in enumerate(results, start=1):
      tweet = result.text
      tidy_tweet = tweet.strip().encode('ascii', 'ignore')

      if len(tweet) == 0:
          print('Empty Tweet')
          continue

      response = client.Sentiment({'text': tidy_tweet})
      csv_writer.writerow({
          'Tweet': response['text'],
          'Sentiment': response['polarity']
      })

      print("Analyzed Tweet {}".format(c))

## count the data in the Sentiment column of the CSV file
with open(file_name, 'r') as data:
   counter = Counter()
   for row in csv.DictReader(data):
      counter[row['Sentiment']] += 1

   positive = counter['positive']
   negative = counter['negative']
   neutral = counter['neutral']

## declare the variables for the pie chart, using the Counter variables for 
"sizes"
colors = ['limegreen', 'dodgerblue', 'darkorchid']
sizes = [positive, negative, neutral]
labels = 'Positif', 'Negatif', 'Netral'
explode = (0.1, 0, 0)

## use matplotlib to plot the chart
plt.pie(
    x=sizes,
    shadow=False,
    colors=colors,
    labels=labels,
    startangle=90,
    explode=explode
)
plt.axis('equal')
plt.title("Sentiment of {} Tweets about {}".format(number, query))
plt.show()

1 个答案:

答案 0 :(得分:0)

在模板文件中,您可以使用文本字段

        <form method="POST" action="/labdashboard/usergivenlab/">
        {% csrf_token %}
            <input type="text" name="textfield" >
            <button type="submit">Submit</button>
        </form>

然后在你的urls.py中定义视图

url(r'usergivenlab/$',views.usergivenlab,name='usergivenlab')

在views.py中,您可以使用POST方法获取使用输入

usergivenip = request.POST.get('textfield', None)