Как запустить внешний файл python в html
Я хочу использовать мой html файл для ввода данных пользователем, затем я хочу использовать мою программу python для обработки моих данных, а затем я хочу, чтобы мой html показывал ответ
HTML часть `
{% extends 'base.html' %}
{% block title %}Home{% endblock title %}Home
{% block body %}
<style>
#body {
padding-left:100px;
padding-top:10px;
}
</style>
<div id="body">
<br>
<marquee width="750px">
<h4>My name is ChatXBot. I'm your Childs Friend. Talk to me. If you want to exit, type Bye!</h4>
</marquee>
<br>
<form action="/external" method="post">
{% csrf_token %}
<textarea id="askchat" name="askchat" rows="10" cols="100" placeholder="Start Typing Here" required></textarea>
{{data_external}}<br><br>
{{data1}}
<br>
<input class="btn btn-secondary btn-lg" type="submit" value="Ask">
</form>
</div>
{% endblock body %}
`
Python часть `
#importing the neccesary libraries
import nltk
import numpy as np
import random
import string # to process standard python strings
nltk.download('omw-1.4')
#wow.txt is text collected from https://en.wikipedia.org/wiki/Pediatricsn
f=open('F:\Ayan\WORK STATION (III)\Python\Python Project\chatbot.txt','r',errors = 'ignore')
raw = f.read()
raw=raw.lower()# converts to lowercase
nltk.download('punkt') # first-time use only
nltk.download('wordnet') # first-time use only
sent_tokens = nltk.sent_tokenize(raw)# converts to list of sentences
word_tokens = nltk.word_tokenize(raw)# converts to list of word
sent_tokens[:2]
word_tokens[:2]
lemmer = nltk.stem.WordNetLemmatizer()
#WordNet is a semantically-oriented dictionary of English included in NLTK.
def LemTokens(tokens):
return [lemmer.lemmatize(token) for token in tokens]
remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)
def LemNormalize(text):
return LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))
GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up","hey",)
GREETING_RESPONSES = ["hi", "hey", "*nods*", "hi there", "hello", "I am glad! You are talking to me"]
def greeting(sentence):
for word in sentence.split():
if word.lower() in GREETING_INPUTS:
return random.choice(GREETING_RESPONSES)
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
def response(user_response):
ChatBot_response=''
sent_tokens.append(user_response)
TfidfVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')
tfidf = TfidfVec.fit_transform(sent_tokens)
vals = cosine_similarity(tfidf[-1], tfidf)
idx=vals.argsort()[0][-2]
flat = vals.flatten()
flat.sort()
req_tfidf = flat[-2]
if(req_tfidf==0):
ChatBot_response=ChatBot_response+"I am sorry! I don't understand you"
return ChatBot_response
else:
ChatBot_response = ChatBot_response+sent_tokens[idx]
return ChatBot_response
flag=True
print("ChatXBot: My name is ChatXBot. I'm your Friends. Talk to me. If you want to exit, type Bye!")
print(".")
while(flag==True):
user_response = input()
user_response=user_response.lower()
if(user_response!='bye'):
if(user_response=='thanks' or user_response=='thank you' ):
flag=False
print("ChatBot: You are welcome..")
else:
if(greeting(user_response)!=None):
print("ChatBot: "+greeting(user_response))
else:
print("ChatBot: ",end="")
print(response(user_response))
sent_tokens.remove(user_response)
else:
flag=False
print("ChatBot: Bye!")
`
Я пробовал использовать Django, но получил много ошибок в этом блоке кода, который я взял с GitHub, будет принимать ввод пользователя, затем попытается понять и затем покажет нам ответ через текстовый файл, который я предоставил
если вы хотите, чтобы все выполнялось на стороне клиента, я думаю, вам следует использовать pyscript иначе вы должны выполнять весь ваш код python в программе на стороне сервера, такой как django, и отправлять результат на клиент с соответствующими библиотеками html/css/js