简体   繁体   中英

How to run external python file in html

I want to use my html file to take user input and then I want to use my python program to process my input and then I want my html shows the answer

HTML Part `

{% 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 part `

#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!")

`

I have tried using Django but got lots of error in this block of code that I have taken from GitHub will take user input and then try to understand and then shows relent answer to us through the text file that I have provided

if you want every thing run in client side I think you should use pyscript otherwise you must execute all your python code in server side program like django and send result to client with proper html/css/js libraries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM