I'm very new to python/programing, and, i've been playing with a small random choice generator. I'm really happy with how everything is working so far, but I'm having a problem with the if statement. how do I go about signaling that the if should point to the first generated choice from table Desert, and not generate a second choice? I've tried nesting the if statement in the print command, but got a lot of syntax errors. Here is the code:
import random
import sys
Name = ['Dave', 'Suzane', 'Jim', 'Diana']
Appitizers = ['Spinach & Artichoke Dip', 'Crispy Green Beans', 'Half Chicken Quesadila', 'None, for me, just the main course please']
MainCourse = ['Steak', 'Sea Food', 'Grilled Chicken', 'House Salad', 'Rib Sanwich', 'Soup of the Day']
Desert = ['Pie of the Day', 'Chocolate Moose', 'Cheeze Cake', "No Thanks, I'm Full!"]
Goodbye = ['Captian', 'Monsiure', 'Sir', 'Madame',]
Goodbye2 = ['Come back again!', 'See you soon', 'Thank you for stopping by', 'Thank you for choosing us!']
print("Hello ", random.choice(Name), "tonight you're meal will be:")
print("Appitizer:", random.choice(Appitizers))
print("Followed by Main Coure:", random.choice(MainCourse))
print("And finally Desert:", random.choice(Desert))
if random.choice(Desert)=="No Thanks, I'm Full!": print('Farwell!', random.choice(Goodbye1)), sys.exit()
print(random.choice(Goodbye2))
Thanks!
Assign the result of random.choice(Desert) to a variable, and use it in both places where it's applicable. (and while you're at it, change Goodbye1 to a variable that exists, such as Goodbye)
x = random.choice(Desert)
print("And finally Desert:", x)
if x=="No Thanks, I'm Full!":
print('Farwell!', random.choice(Goodbye))
sys.exit()
Related
Whenever I run this code with the chopped = first_word.split() line I get an error (the window closes instantly).
import tkinter as tk
win = tk.Tk()
win.title("Conversation")
win.iconbitmap("cake.ico")
win.geometry("600x700")
#Lists
Hellos = ["greetings", 'hello', 'greetings', 'hi']
gday = ['good', 'great', 'incredible', 'not bad', 'okay']
bday = ['bad', 'awful', 'not the best', 'terrible']
fw_label = tk.Label(win, text="Hello user, it's nice to meet you.")
fw_label.pack()
first_word = tk.Entry()
first_word.pack()
chopped = first_word.split()
But when I change the line first_word = tk.Entry() to first_word="A normal string" , the split method highlights and when I hover it it gives its description, which wasn't happening with ```first_word = tk.Entry()``.
I've ran into this problem when using libraries like opencv, may I know what's causing it not to work?
The solution is simple. You have to make a function to be called while pressing the submit button. And the statement chopped = first_word.get().split() should be inside that function.
Coming to the error part, it was because first_word is a tkinter entry object without any attribute split().
The split method works only for strings. To get the text entered into the entry widget in form of string, you need to use the get() method...
import tkinter as tk
def click():
chopped = first_word.get().split()
print(chopped)
win = tk.Tk()
win.title("Conversation")
# win.iconbitmap("cake.ico")
win.geometry("600x700")
#Lists
Hellos = ["greetings", 'hello', 'greetings', 'hi']
gday = ['good', 'great', 'incredible', 'not bad', 'okay']
bday = ['bad', 'awful', 'not the best', 'terrible']
fw_label = tk.Label(win, text="Hello user, it's nice to meet you.")
fw_label.pack()
first_word = tk.Entry()
first_word.pack()
tk.Button(win, text="Submit", command=click).pack()
win.mainloop()
So, you get the text of the entry using the get() method and then split it
Note : The statement chopped = first_word.get().split() should be inside the function because if its outside it, it would be executed at the time of the creation of the entry widget and using get() there would result in an empty value as the entry doesn't contain anything at that point
Maybe this could work
Change
chopped = first_word.split()
to
chopped = first_word.get().split()
I'm unable to reply my comment on your last question because of my low reputation. https://www.shapedivider.app/ here you would easily make the curves you want and embed the code to your project. I use this often.
I am working on a chatbot and the code is -
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from chatterbot.trainers import ChatterBotCorpusTrainer
import nltk
import numpy as np
import random
import string # to process standard python strings
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import os
language = 'en'
remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)
GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up","hey","hii")
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:
greetinput = random.choice(GREETING_RESPONSES)
return greetinput
def response(user_response):
robo_response=''
user_response = str(user_response)
robo_response = robo_response+return_response
return robo_response
flag=True
my_bot = ChatBot(name='PyBot', read_only=True,logic_adapters=['chatterbot.logic.MathematicalEvaluation','chatterbot.logic.BestMatch'])
small_talk = ['hi there!',
'hi!',
'how do you do?',
'how are you?',
'i\'m cool.',
'fine, you?',
'always cool.',
'i\'m ok',
'glad to hear that.',
'i\'m fine',
'glad to hear that.',
'i feel awesome',
'excellent, glad to hear that.',
'not so good',
'sorry to hear that.',
'what\'s your name?',
'i\'m pybot. ask me a math question, please.']
math_talk_1 = ['pythagorean theorem',
'a squared plus b squared equals c squared.']
math_talk_2 = ['law of cosines',
'c**2 = a**2 + b**2 - 2 * a * b * cos(gamma)']
list_trainer = ListTrainer(my_bot)
for item in (small_talk, math_talk_1, math_talk_2):
list_trainer.train(item)
corpus_trainer = ChatterBotCorpusTrainer(my_bot)
corpus_trainer.train('chatterbot.corpus.english')
openremark = "ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!"
print("ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!")
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("ROBO: You are welcome..")
else:
if(greeting(user_response)!=None):
print("ROBO: "+greeting(user_response))
else:
print("ROBO: ",end="")
print("func call user_response")
print(user_response)
print("end")
user_response = str(user_response)
print(response(user_response))
else:
flag=False
offremark2 = "Bye! take care"
print("ROBO: Bye! take care..")
On run command it is not working fine -
ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!
hi
ROBO: hi there
gaurav
ROBO: func call user_response
gaurav
end
user_response
gaurav
type
<class 'str'>
end
dummy check
you are busy
dummy end
user_response
gaurav
Traceback (most recent call last):
File "chatbot-new-1.py", line 118, in <module>
print(response(user_response))
File "chatbot-new-1.py", line 46, in response
robo_response = robo_response+return_response
TypeError: must be str, not Statement
It is working fine for greeting and BYE message but when it has to work with CHATTERBOT and CHATTERBOT_CORPUS it is giving an error.
Traceback (most recent call last):
File "chatbot-new-1.py", line 118, in <module>
print(response(user_response))
File "chatbot-new-1.py", line 46, in response
robo_response = robo_response+return_response
TypeError: must be str, not Statement
TypeError: must be str, not Statement
I even tried with making user_response string first and also with for loop so that it work for each singular element but it turn up the same message. I am not able to resolve the error and didnt get any answer for the same or similar question.
What is return_response ? It doesn't look like it's defined.
Maybe replace this :
robo_response = robo_response+return_response
by this :
robo_response = robo_response+user_response
You can use this code for making a best bot first install English folder from chatterbot corpse from GitHub
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot
bot = ChatBot('Text')
conv = open('english/ai.yml','r').readlines()
bot.set_trainer(ListTrainer)
bot.train(conv)
while True:
request = input('you:')
response = bot.get_response(request)
print('Bot: ', response())
I wrote a push notification scheduler in python for research, which will handle sending notifications via NODE .js. It works beautifully on my Mac, no problems. I built a server elsewhere to handle the scheduler, since it's always on. The server runs Debian Wheezy, for reasons I'm not in control of. However, whenever I try to run the code, I get:
File "scheduler.py", line 148, in send_notifications
s.enter(5, 1, notification, kwargs={'notify': 'Welcome to the Study!'})
TypeError: enter() got an unexpected keyword argument 'kwargs'
Still works perfectly on my Mac. I've checked to make sure that all my imported libraries have been downloaded via pip3, but I just can't figure out what my problem is. I've checked out other people with this error on stackoverflow and various other sources, but I wasn't sure that they were having a similar problem to my problem, mostly a class call issue, and I don't think this is that. I've attached the code, although I'm not sure if that helps any. I mean, it's not the cleanest code in the world, but I'm more fluent in mobile dev than python. Any recommendations?
import time #this need is obvious
import datetime as dt
import sched
from datetime import datetime
from datetime import timedelta
from subprocess import call #needed to call terminal commands
#Don't forget to chmod +x this python application so that you can sudo out.
#this order of the notifications that will be run, in an array
listOfNotificationNames = ['weather', 'sched', 'thermo', 'manualKitchen', 'frontDoor', 'garage', 'window', 'solar', 'backDoor', 'garage', 'frontDoor',
'manualKitchen', 'solar', 'energyCom', 'alarm', 'weather', 'sched', 'solar', 'manualKitchen', 'thermo', 'frontDoor', 'garage', 'manualKitchen',
'autokitchen', 'backDoor', 'frontDoor', 'manualKitchen', 'garage', 'sensor', 'solar', 'window', 'energyCom', 'alarm', 'weather', 'sched', 'thermo',
'manualKitchen', 'frontDoor', 'garage', 'tvenergy', 'window', 'garage', 'backDoor', 'solar', 'frontDoor', 'manualKitchen', 'energyCom', 'alarm',
'weather', 'sched', 'solar', 'thermo', 'manualKitchen', 'frontDoor', 'manualKitchen', 'garage', 'backDoor', 'milk', 'garage', 'frontDoor', 'manualKitchen',
'autokitchen', 'energyCom', 'alarm', 'weather', 'solar', 'sched', 'thermo', 'manualKitchen', 'backDoor', 'garage', 'window', 'frontDoor', 'autokitchen',
'manualKitchen', 'frontDoor', 'solar', 'garage', 'energyCom', 'alarm']
#Dictionary of what the above short names connect to. Take short names, and connect them to full length notifications
listOfNotificationText = {'garage': 'Your garage door has opened', 'frontDoor': 'Your front door has opened', 'backDoor': 'Your back door has opened',
'energyCom': 'Your daily energy consumption is: 33.5 kWh', 'thermo': 'Your thermostat has been changed to 73 degrees', 'weather': 'The weather for the day is: Cloudy and cool',
'solar': 'The solar cell battery status is 52%', 'alarm': 'Tomorrow’s alarm is set for 9am', 'sched': 'Today’s schedule includes: ',
'milk': 'Don’t forget to get milk on your way home today.', 'manualKitchen': 'A light in the kitchen has been turned on',
'sensor': 'The sensor above the door is not responding. Please check on its status.',
'tvenergy': 'Your television utilizes 2 watts of energy when not in use. It will be powered off when not in use from now on.',
'window': 'The bedroom window has been opened to cool the room.'}
#test code, can be used to test the notification system
time1 = now+timedelta(seconds=30)
time2 = now+timedelta(seconds=60)
time3 = now+timedelta(seconds=90)
testList = [dt.datetime(now.year, now.month, now.day, time1.hour, time1.minute, time1.second),
dt.datetime(now.year, now.month, now.day, time2.hour, time2.minute, time2.second),
dt.datetime(now.year, now.month, now.day, time3.hour, time3.minute, time3.second)]
#empty list to be filled
listOfTimeDelays = [0, 0, 0]
#takes all the lists above, and figures out how long each of them are from when I started the study.
#This creates a giant list of delays from the day I hit start
def calculateMinutesIntoSeconds(testList, listOfTimeDelays):
i = 0
for member in testList:
print(member)
listOfTimeDelays[i] = ((member-dt.datetime(now.year, now.month, now.day, now.hour, now.minute, now.second)).total_seconds())
print(listOfTimeDelays[i])
i= i+1
# Note that you have to specify path to script
#This call runs the notification.
#Create a scheduler.
s = sched.scheduler(time.time, time.sleep)
#Takes a notification text and sends ends out the notification.
def notification(notify='failure to properly fill notification'):
call(["node", "app.js", notify, "send this data"])
#test code. Mostly ignore this
def print_time(a='default'):
print("From print_time", time.time(), a)
def send_notifications():
#calculate all of the many times delays
calculateMinutesIntoSeconds(testList, listOfTimeDelays)
# calculateMinutesIntoSeconds(listOfTimesDay1, listOfTimeDelays)
# calculateMinutesIntoSeconds(listOfTimesDay2, listOfTimeDelays)
# calculateMinutesIntoSeconds(listOfTimesDay3, listOfTimeDelays)
# calculateMinutesIntoSeconds(listOfTimesDay4, listOfTimeDelays)
# calculateMinutesIntoSeconds(listOfTimesDay5, listOfTimeDelays)
print("Time marker for beginning of study: ", time.time())
#counter needed for calls
i = 0
#Just notify people that the study has started.
s.enter(5, 1, notification, kwargs={'notify': 'Welcome to the Study!'})
#This for loop fills the scheduler with every notification that needs to be sent.
for member in listOfTimeDelays:
#takes one of the time delays, a priority (I just made them all 1), and then sends the right notification
s.enter(member, 1, notification, kwargs={'notify': listOfNotificationText[listOfNotificationNames[i]]})
#Incriments the counter to make sure you get the next notification
i = i+1
#runs the scheduler
s.run()
#Marks the end of the study
print("Time marker for end of study: ",time.time())
#Calls the above method
send_notifications()
UPDATE:
Hmm, on further inspection, it looks like the Wheezy system defaults 3.2 and won't accept a request for anything higher than that. Looks like it accepts "argument" but as Klaus suggested, argument also needs notify to be in the same area as the sent notification.
So now it looks like
s.enter(5, 1, notification, argument={'notify: Welcome to the Study!'})
#This for loop fills the scheduler with every notification that needs to be sent.
for member in listOfTimeDelays:
notification = 'notify: ' + listOfNotificationText[listOfNotificationNames[i]]
#takes one of the time delays, a priority (I just made them all 1), and then sends the right notification
s.enter(member, 1, notification, argument={notification)
#Incriments the counter to make sure you get the next notification
i = i+1
Thanks for the assistance with this.
sched.Scheduler only accepts a kwargs argument from Python 3.3 onwards. I guess you are running an older version on your Debian machine.
Here is the code I'm working with:
import sys
from tkinter import *
from random import choice
def motiv():
motiv1 = mLabel = Label(text='Waste not, want not', fg="red").pack()
motiv2 = mLabel = Label(text='Sticks and stones', fg="red").pack()
motiv3 = mLabel = Label(text='Keep holding on', fg="red").pack()
motiv4 = mLabel = Label(text='Hold On, Pain Ends', fg="red").pack()
ranMotiv = [motiv1, motiv2, motiv3, motiv4]
print (choice(ranMotiv))
mGui = Tk()
mGui.geometry('450x450+500+150')
mGui.title('RMM')
mLabel = Label(text='Welcome to the Random Motivation Machine', fg="red").pack()
mButton = Button(text = "Click for Some Motivation", command = motiv)
mButton.pack()
mGui.mainloop()
There are no errors, but it keeps printing out all of those texts at the same time, when I'm wanting it to only print out only one of them at random.
My goal is to have someone press the button and out pops a random phrase in the GUI window.
So someone presses the button and only one of any of the four text phrases comes out on the window:
1.Waste not, want not.
2.Sticks and stones
3.Keep holding on.
4.Hold on, Pain Ends.
I believe my troubles are arising from this area right here:
ranMotiv = [motiv1, motiv2, motiv3, motiv4]
print (choice(ranMotiv))
Does anyone have any ideas? This is just a very small pet project of mine. I've only been using Python for less than a few months so I'm not very astute. I'm running Python 3.2.5 by the way. Thank you all in advance.
I originally posted this as a comment, but it turned out to be the answer, so I'm reposting it here:
The problem is that Label(text='Waste not, want not', fg="red").pack() packs the label right away. Doing this with all labels causes them to be packed. It doesn't matter if you call random.choice later because the labels have already been packed into your GUI.
If you want to create a random label from a pool of labels, What you want to do is this:
def motiv():
myLabels = ['Waste not, want not', 'Sticks and stones', 'Keep holding on', 'Hold On, Pain Ends']
chosenLabel = random.choice(myLabels)
randMotiv = Label(text=chosenLabel, fg="red").pack()
How about this:
from tkinter import *
from random import choice
# Place the messages outside of the function so that they are not
# re-created each time the button is pressed
messages = ['Waste not, want not', 'Sticks and stones',
'Keep holding on', 'Hold On, Pain Ends']
def motiv():
# Just update the text of the Label instead of create a whole new one
message["text"] = choice(messages)
mGui = Tk()
mGui.geometry('450x450+500+150')
mGui.title('RMM')
mLabel = Label(text='Welcome to the Random Motivation Machine', fg="red").pack()
mButton = Button(text = "Click for Some Motivation", command = motiv)
mButton.pack()
# Make a Label to hold the messages that will be updated with each click of the button
message = Label(fg="red")
message.pack()
mGui.mainloop()
Instead of just tacking a new message to the bottom of the GUI, this method is cleaner and just updates the text of the message. It also fixes the problem of messages running off of the GUI (you can see this by clicking the button like 30 times).
I am writing a script that works like google suggest. Problem is that I am trying to get a suggestion for next 2 most likely words.
The example uses a txt file working_bee.txt. When writing a text "mis" I should get suggestions like "Miss Mary , Miss Taylor, ...". I only get "Miss, ...". I suspect the Ajax responseText method gives only a single word?
Any ideas what is wrong?
# Something that looks like Google suggest
def count_words(xFile):
frequency = {}
words=[]
for l in open(xFile, "rt"):
l = l.strip().lower()
for r in [',', '.', "'", '"', "!", "?", ":", ";"]:
l = l.replace(r, " ")
words += l.split()
for i in range(len(words)-1):
frequency[words[i]+" "+words[i+1]] = frequency.get(words[i]+" "+words[i+1], 0) + 1
return frequency
# read valid words from file
ws = count_words("c:/mod_python/working_bee.txt").keys()
def index(req):
req.content_type = "text/html"
return '''
<script>
function complete(q) {
var xhr, ws, e
e = document.getElementById("suggestions")
if (q.length == 0) {
e.innerHTML = ''
return
}
xhr = XMLHttpRequest()
xhr.open('GET', 'suggest_from_file.py/complete?q=' + q, true)
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
ws = eval(xhr.responseText)
e.innerHTML = ""
for (i = 0; i < ws.length; i++)
e.innerHTML += ws[i] + "<br>"
}
}
xhr.send(null)
}
</script>
<input type="text" onkeyup="complete(this.value)">
<div id="suggestions"></div>
'''
def complete(req, q):
req.content_type = "text"
return [w for w in ws if w.startswith(q)]
txt file:
IV. Miss Taylor's Working Bee
"So you must. Well, then, here goes!" Mr. Dyce swung her up to his shoulder and went, two steps at a time, in through the crowd of girls, so that he arrived there first when the door was opened. There in the hall stood Miss Mary Taylor, as pretty as a pink.
"I heard there was to be a bee here this afternoon, and I've brought Phronsie; that's my welcome," he announced.
"See, I've got a bag," announced Phronsie from her perch, and holding it forth.
So the bag was admired, and the girls trooped in, going up into Miss Mary's pretty room to take off their things. And presently the big library, with the music-room adjoining, was filled with the gay young people, and the bustle and chatter began at once.
"I should think you'd be driven wild by them all wanting you at the same minute." Mr. Dyce, having that desire at this identical time, naturally felt a bit impatient, as Miss Mary went about inspecting the work, helping to pick out a stitch here and to set a new one there, admiring everyone's special bit of prettiness, and tossing a smile and a gay word in every chance moment between.
"Oh, no," said Miss Mary, with a little laugh, "they're most of them my Sunday- school scholars, you know."
Looking at your code I believe you are not sending the correct thing to Apache. You are sending apache a list and apache is expecting a string. I would suggest changing your return to json:
import json
def complete(req, q):
req.content_type = "text"
return json.dumps([w for w in ws if w.startswith(q)])