I'm working on a chatbot which has two scenarios.
1: When the user types a question, if that question is available it training dataset, It picks a response for that question from the training dataset.
2: If the question typed by user is not available in the dataset, system gives response from default answers which are defined with in the code.
My problem is, when the system gets a question statement that is not in the training data, it picks a random answer from the code (Fine). But from that point, it starts giving default answers no matter which question we ask. It never picks an answer from training data despite having that particular question and its answer in the training data.
The entire code is too large to paste here. I'm writing just those functions where the problem occurs. Hope someone could help me with this.
def response(sentence, userID='123', show_details=False):
results = classify(sentence)
# if we have a classification then find the matching intent tag
if results:
# loop as long as there are matches to process
while results:
#some if else statements to match the question
results.pop(0)
while not results:
pairs = (
(r'I need (.*)',
("Why do you need %1?",
"Would it really help you to get %1?",
"Are you sure you need %1?")),
(r'Why don\'t you (.*)',
("Do you really think I don't %1?",
"Perhaps eventually I will %1.",
"Do you really want me to %1?"))
)
aida_chatbot = Chat(pairs, reflections)
def aida_chat():
aida_chatbot.converse()
def demo():
aida_chat()
if __name__ == "__main__":
demo()
else:
response()
# sentence = sys.stdin.readline()
sys.stdout.write("> ")
sys.stdout.flush()
classify(sentence=sys.stdin.readline())
while True:
response(sentence=sys.stdin.readline())
When I put the pairs outside the while statement, (e.g in else statement after the if statement is closed), program never enters the else statement and this part of code is never executed.
Cany anybody help me with this?
if __name__ == "__main__":
demo()
else:
response()
You are not passing question text from this response function call. Just pass your question as an argument from this response function call.
Related
I am trying to make a sort-of AI thing with Python, but I've got stuck on some part.
When the AI says something, (says hello at the beginning), it gives you the ability to input text, once you've entered that, it would go through if 'keyword' in answer statements to provide a reply. Once it replies, it calls the AImain() function, restarting that process. I can't seem to get it to restart, as compiling would just say hello initially (as intended), but give no input text ability, which results in the script ending. Here's the code:
def AImain():
response = input("YOU:")
if 'Hello' or 'Hi' in answer:
print(random.choice(welcomeMessages))
AImain()
I'm new to python and I don't understand why this isn't working.
Thanks!
Your code has an indentation problem at the Aimain() function and we can't see how answer is declared. You are assigning the input to response but reading answer in your code.
Here is my suggestion to your code
response = "Hi" #you can eliminate this, assuming response is declared somewhere else
def AImain():
global response
response = input("You:")
while response == 'Hello' or response == "Hi":
print(random.choice(welcomeMessages))
AImain()
I'm quite new to coding. I've wrote a simple piece of code which will take a URL as an input, load the URL and put the status code for that URL in a variable. I have put this in a function. But when I run the code I get no errors and yet the function won't run. It seems like the interpreter is just flying past my function. I know I have some simple error but no matter how much I search I can't fix it. Please help me understand. Oh, and the code is incomplete. But the function should run.
import urllib.request, click, threading
url = input("Enter domain name >> \n")
def get_stat():
status = urllib.request.urlopen("http://"+url).getcode()
if status == 200:
return "Site loads normally!\nHost Said: '%s'!" %(str(status))
else:
return "Site Needs To Be Checked!\nHost Said: '%s'!" %(str(status))
get_stat()
if click.confirm("Would you like to set a uptime watch?"):
click.echo("You just confirmed something!!")
count = input("Enter the number of times you wish your site to be checked: ")
interval = input("Enter the time interval for status requests (Time is in minutes): ")
You function certainly is working. The problem you are facing is that you are returning a value from get_stat() (this is what the return statement does) but you never actually say that this value should print.
My guess is you want to print the values that are returned in which case you need to add the print statement:
print(get_stat())
Or you could store what the value as a variable:
a = get_stat()
print(a)
As said in quamrana's comment below although the following method is considered bad practice you can put the print() statement inside your function for debugging purposes and replace it later:
if status == 200:
print("Site loads normally!\nHost Said: '%s'!" %(str(status)))
else:
print("Site Needs To Be Checked!\nHost Said: '%s'!" %(str(status)))
This will prove that the function is indeed being executed.
This post might help you understand a little bit better what the return statement does and how you can get values from it.
def you ():
gi=input("what up")
if gi in ["Nothing much", "nothing much", "nothing"]:
print("cool")
you()
elif gi in ["stuff"]:
print("sounds good")
I apparently cannot do this, however In a bigger program I am working on, I have a function that is used twice, however based of the user input, different results happen, so I tried to include my large function, and like the above program have an if else be continued throughout the function, because there are different options for user input, based on where the person is in the program.
I am just trying to figure out a good way to run a game, where the beginning is the same (function), however the game can progress in different ways, therefore a function won't work for all of it, so I just want to know if I can have an if else statement run through a function like in the small example above?
As James already said, no you cannot continue an if statement outside of a function. Referring to your question if functions are useful in a larger program: yes they are. You can use data generated in functions in your main program or other functions by returning your results. For instance:
def you ():
gi=input("what up")
return gi
result = you()
if result in ["Nothing much", "nothing much", "nothing"]:
print("cool")
elif result in ["stuff"]:
print("sounds good")
So, instead of Python basically following the cascading script as it usually does is it possible where it will never end unless you type "end" and you can ask it any question over & over again?
I'm basically creating a bot where you basically activate it by typing 'Cofo, activate' and it will reply 'Cofo activated, how may I help you today?' and from there you can ask it things like 'What's the weather today' and 'what's 9 + 4' etc, etc. A little like Jarvis but without actual speech, more text based.
Sorry I haven't given a very good explanation, I can't really explain what I want but hopefully you understand.
the way to do this with a while loop:
while True:
user_data = raw_input('What do you want? ')
if user_data == 'quit': break
else:
print 'I can\'t do "{}" yet.'.format(user_data)
All this script does is echo back your input, so ignore the details - the main thing is that the loop runs until the user enters 'quit' (or whatever word you want to specify).
As noted by #cricket_007, you need a while loop. Check the tutorial for a simple introduction and the docs for a formal syntax definition.
Asking indefinitely for user input is a common pattern, be sure to check out this canonical question about a related issue: asking for user input until a valid response is provided.
I'm experimenting/having a little fun with wave robot python apiv2.
I made a little 8ball app for the robot which works fine, and now I'm trying to make a trivia app.
I've never programmed in Python but I'm pretty sure my syntax is correct. Here is the relevant code:
elif (bliptxt == "\n!strivia"):
reply = blip.reply()
if (triviaStatus != "playing"):
reply.append("Trivia Started!")
triviaStatus = "playing"
else:
reply.append("Trivia is already running!")
elif (bliptxt == "\n!etrivia"):
reply = blip.reply()
if (triviaStatus == "playing"):
reply.append("Trivia Ended!")
triviaStatus = "stopped"
else:
reply.append("Trivia is not running! To start trivia, type !strivia")
else: (snipped out)
Okay so basically I want it to work so that when someone blips "strivia" the bot recognizes that someone wants to play so it first checks a variable called triviaStatus to see if we are already playing and goes from there. Pretty simple stuff.
In order for this to work (and, actually, this code is really meant to test this question out) the variables would need to effectively be like the php $_SESSION variables - that is, it remembers the value of the variable every time someone blips and does not reset each time.
Nevertheless, whether or not that is the case (if it isn't then I assume I can do the same thing by saving variable settings in a txt file or something) I am baffled because the code above does not work at all. That is to say, the robot is not replying on !strivia or on !etrivia. If the variables didn't save then if anything the robot should just reply with "Trivia Started" or with "Trivia is not running!" each time. But it just does not reply at all.
If I remove the check for triviaStatus, the robot DOES reply. But then there's no logic and I can't test my question out.
I also tried making a !trivstatus where it would reply back with
"Trivia status is " + triviaStatus
but that ALSO choked up. Why is it that every time I want to USE triviaStatus, the bot just dies? Note that I am able to SET triviaStatus fine (I just can't ever check what the output is by replying with it....)
So, to sum this up...how come the above code does not work but the following code DOES work:
elif (bliptxt == "\n!strivia"):
reply = blip.reply()
reply.append("Trivia Started!")
trivia_status = "playing"
elif (bliptxt == "\n!etrivia"):
reply = blip.reply()
reply.append("Trivia Ended!")
trivia_status = "stopped"
Thanks!
It seems that you should rename triviaStatus to trivia_status and make sure that trivia_status has some value e.g., bind it to None before the first use. Otherwise your code might raise UnboundLocalError or NameError exceptions due to triviaStatus/trivia_status doesn't refer to any object.