I seem to be having an issue with looping through the data that I pulled from a url in my Alexa skill, here is my sample code:
def get_elevator_status():
session_attributes = {}
card_title = "Septa Elevator Status"
reprompt_text = ""
should_end_session = False
response = urllib2.urlopen(API_BASE_URL + "/elevator")
septa_elevator_status = json.load(response)
for elevators in septa_elevator_status['results']:
speech_output = "The following elevators are out of service." "On " + elevators['line'] + " at station " + elevators['station'] + " the " + elevators['elevator'] + " elevator has " + elevators['message']
If I run the code in python shell and print out the results (if there are multiple outages) it prints out all lines. But when I test my Alexa skill and ask for outages it only reports back one result even though there are multiple elevator outages. Am I missing something for this to work? Should this code loop through and say all results found right?
can you post the 'response' json, my guess is that the json is not formed correctly
While looping through the result set everytime you are overwriting speech_output with that particular elevators. Instead, you have to concatenate every result to speech_output.
for elevators in septa_elevator_status['results']:
speech_output = speech_output + " <s> The following elevators are out of service." "On " + elevators['line'] + " at station " + elevators['station'] + " the " + elevators['elevator'] + " elevator has " + elevators['message'] + "</s>"
<s> is the sentence tag, use it only if you are using SSML.
Related
I am trying to build an APA citation generator, asking the user for name of author, date, etc. And returning the correct reference structure. When it comes to citing a book, the title has to come in italics. I found a way for the output to come in italics using
f'\033[3m{title}\033[0m'
The problem is that I want the user to be able to copy and paste the reference in their document, however if you try to copy the output on the console, and paste it anywhere, the italic formatting is lost.
This is the part of the code:
reference = lastname + ", " + name[0] + ". " + "(" + year + "). " + f'\033[3m{title}\033[0m' + ". " + place + ": " + editorial + "."
I am making a type of quiz, and want to know how to compare the results to a text file. After answering the questions with prompted input, the function will return a four digit code. I want that four digit code to be compared to "truecode" in a text file I've written out with additional information like this:
villagername,personality,birthday,zodiac,truecode,species
Ankha,snooty,September 22nd,Virgo,A420,Cat
Bangle,peppy,August 27th,Virgo,A330,Tiger
Bianca,peppy,December 13th,Sagittarius,A320,Tiger
Bob,lazy,January 1st,Capricorn,A210,Cat
Bud,jock,August 8th,Leo,A310,Lion
I want this other information to be printed out.
print("Your villager is " + villagername)
print("They are a " + personality + " type villagers and of the " + species + " species.")
print("Their birthday is " + birthday + " and they are a " + zodiac)
print("I hope you enjoyed this quiz!")
I cannot figure out how to extract this information and compare it to what I have. Should I use a list or a dictionary? I'm getting frustrated trying to Google my question and wondering if I went around it all wrong.
How do I compare the four digit code (that will be returned from another function) to "true code" and get everything spit out like above?
import csv
def compare_codes(true_code):
with open(''file.txt) as csvfile:
details_dict = csv.reader(csvfile)
for i in details_dict:
if i['truecode'] == tru_code:
print("Your villager is:",i['villagername'])
print("They are a " + i['personality'] + " type villagers and of the " + i['species'] + " species.")
print("Their birthday is " + i['birthday'] + " and they are a " + i['zodiac'])
print("I hope you enjoyed this quiz!")
break
compare_codes('A420')
Above code reads the text file and compares the input with truecode value in your file and displays the info.
import csv
def get_data(filename):
with open(filename) as f:
reader = csv.DictReader(f, delimiter=',')
data = {row['truecode']: row for row in reader}
return data
def main():
filename = 'results.txt'
data = get_data(filename)
code = input('Enter code: ')
try:
info = data[code]
print("Your villager is " + info['villagername'])
print("They are a " + info['personality'] +
" type villagers and of the " + info['species'] + " species.")
print("Their birthday is " +
info['birthday'] + " and they are a " + info['zodiac'])
print("I hope you enjoyed this quiz!")
except KeyError:
print('Invalid code')
if __name__ == "__main__":
main()
The type of file that you have is actually called a CSV file. If you wanted to, you could open your text file with any spreadsheet program, and your data would show up in the appropriate cells. Use the csv module to read your data.
import csv
def get_quiz_results(truecode):
with open('your-text-file.txt') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
# row is a dictionary of all of the items in that row of your text file.
if row['truecode'] == truecode:
return row
And then to print out the info from your text file
truecode = 'A330'
info = get_quiz_results(truecode)
print("Your villager is " + info["villagername"])
print("They are a " + info["personality"] + " type villagers and of the " + info["species"] + " species.")
print("Their birthday is " + info["birthday"] + " and they are a " + info["zodiac"])
print("I hope you enjoyed this quiz!")
When looping over the file, the csv module will turn each line of the file into a dictionary using the commas as separators. The first line is special, and is used to create the dictionary keys.
Im trying to parse a website and save its contents to CSV file but on line
brand = make_rating_sp[0].img["title"].title()
I get the typescript error
for container in containers:
make_rating_sp = container.div.select("a")
brand = make_rating_sp[0].img["title"].title()
product_name = container.div.select("a")[2].text
shipping = container.findAll("li", {"class": "price-ship"})[0].text.strip().replace("$",
"").replace(" Shipping", "")
print("brand: " + brand + "\n")
print("product_name: " + product_name + "\n")
print("shipping: " + shipping + "\n")
f.write(brand + ", " + product_name.replace(",", "|") + ", " + shipping + "\n")
You are most likely seeing IndexError: list index out of range, but you may also encounter problems if the make_rating_sp list contains elements, but the specific a tag at the specified index does not contain an img tag.
Try adding something like:
brand = ""
try:
brand = make_rating_sp[0].img["title"].title()
except:
pass
Often in Python you will want to catch specific exceptions, but in this instance a generic solution is probably sufficient.
I'm having a bit a problem. I'm still very new to python. So dict's are very new to me. I know of solve problems as I go and hopefully learn from my mistakes.
So the error is below with 'shortURL' in the first text variable. Just wondering what the issue means and how I could go about solving it? I've had a look online and didn't fully understand why as a lot of issues where looking at string but the bit.ly_api just return a URL.
Thanks for any help :)
print("")
print("Welcome to Sole Retriever Tweet Formulator b0.1")
type = (raw_input('What kind of tweet would you like to do?' + '\n' + '1. Store URL + Website Site' + '\n' + '2.Website URL Only' + '\n'))
if type == ('1'):
store1 = (raw_input('What is the store name hosting the Off-White x Converse Raffle? '))
storeURL = (raw_input('What is the direct URL to the raffle? '))
shortURL = b.shorten(storeURL)
text = ('Woof! ' + store1 + ' raffle is now live for the Off-White x Converse Chuck Taylor!' + '\n' + '\n' + shortURL + '\n' + '\n' + 'For raffle details and where to enter check and filter by "live" -' + '\n' + '\n' + 'https://www.soleretriever.com/off-white-x-converse-chuck-taylor/' + '\n' + '\n' + '#soleretriever #offwhite #converse #sneakers')
print (text)
os.system("echo '%s' | pbcopy" % text)
print ('\n')
print ('Copied to Clipboard')
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
twitter.update_status(status=text)
if type == ('2'):
store = (raw_input('What is the store name hosting the Off-White x Converse Raffle? '))
text = ('Woof! ' + store + ' raffle is now live for the Off-White x Converse Chuck Taylor!' + '\n' + '\n' + 'For raffle details and where to enter check and filter by "live" -' + '\n' + '\n' + 'https://www.soleretriever.com/off-white-x-converse-chuck-taylor/' + '\n' + '\n' + '#soleretriever #offwhite #converse #sneakers')
print (text)
os.system("echo '%s' | pbcopy" % text)
print ('\n')
print ('Copied to Clipboard')
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
twitter.update_status(status=text)
The call to b.shorten(storeURL) will return a dict with key/value pairs, including the url. Python will throw that error when you concatenate a string and dict like you're doing in print(). I'd suggest something like:
response = b.shorten(storeURL)
shortURL = response['url']
I'm trying to use the GET users/lookup from the twitter API in a python script to identify screen name based on a list of users IDs. The script doesn't seem to be able to handle 404 errors, as I assume the whole request with 100 user IDs is not found by twitter, so the for loop doesn't even begin. How do I iterate over 100 user IDs at a time, while still respecting the rate limit, if one of the 100 IDs will cause the whole request to 404? Is there a way to handle this error while still getting the response for the other IDs in the same request? My experiments with "except Valueerror" didn't seem to solve this...
I'd very much appreciate any advice or tips you can give!
while total_request_counter <= request_total:
while list_counter_last <= len(list)+100: #while last group of 100 items is lower or equal than total number of items in list#:
while current_request_counter < 180:
response = twitter.users.lookup(include_entities="false",user_id=",".join(list[list_counter_first:list_counter_last])) #API query for 100 users#
for item in list[list_counter_first:list_counter_last]: #parses twitter IDs in the list by groups of 100 to record results#
try: #necessary for handling errors#
results = str(response)
results = results[results.index("u'screen_name': u'",results.index(item)) + 18:results.index("',",results.index("u'screen_name': u'",results.index(item)) + 18)]#looks for username section in the query output#
text_file = open("output_IDs.txt", "a") #opens current txt output / change path to desired output#
text_file.write(str(item) + "," + results + "\n") #adds twitter ID, info lookup result, and a line skip to the txt output#
text_file.close()
error_counter = error_counter + 1
print str(item) + " = " + str(results)
except: #creates exception to handle errors#
text_file = open("output_IDs.txt", "a") #opens current txt output / change path to desired output#
text_file.write(str(item) + "," + "ERROR " + str(response.headers.get('h')) + "\n") #adds twitter ID, error code, and a line skip to the txt output#
text_file.close()
print str(item) + " = ERROR"
continue
print "Succesfully processed " + str(error_counter) + " users of request number " + str(current_request_counter + 1) + ". " + str(179 - current_request_counter) + " requests left until break." #confirms latest batch processing#
print ""
list_counter_first = list_counter_first + 100 #updates list navigation to move on to next group of 100#
list_counter_last = list_counter_last + 100
error_counter = 0 # resets error counter for the next round#
current_request_counter = current_request_counter + 1 #updates current request counter to stay below rate limit of 180#
t = str(datetime.now())
print ""
print "Taking a break, back in 16 minutes. Approximate time left: " + str((len(list)/18000*15)-(15*total_request_counter)) + " minutes. Current timestamp: " + t
print ""
current_request_counter = 0
total_request_counter = total_request_counter + 1
time.sleep(960) #suspends activities for 16 minutes to respect rate limit#