簡體   English   中英

如何使用django在html中運行python腳本並從html輸入表單獲取變量

[英]How to run python script in html using django and get variable from html input form

我有一個情感分析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()

在模板文件中,您可以具有文本字段

        <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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM