Dynamically naming saved dataframes in loop - python

I'm attempting to use the GTab package to query Google Search trends data for every state in the US, but am having some trouble getting my loop to work.
For one state it's easy enough to do this, and new_query produces a dataframe.
t = gtab.GTAB()
t.set_options(pytrends_config={"geo": "US-NY", "timeframe": "2020-09-01 2020-10-01"})
query = t.new_query("weather")
To loop through I'm trying to use a dict to assign geo dynamically. However, I can't figure out how to do the same for the df name (query).
state_abbrevs = {
'Alabama': 'AL',
'Alaska': 'AK',
'Arizona': 'AZ',
'Arkansas': 'AR',
'California': 'CA',
'Colorado': 'CO',
'Connecticut': 'CT',
'Delaware': 'DE',
'District of Columbia': 'DC',
'Florida': 'FL',
'Georgia': 'GA',
'Guam': 'GU',
'Hawaii': 'HI',
'Idaho': 'ID',
'Illinois': 'IL',
'Indiana': 'IN',
'Iowa': 'IA',
'Kansas': 'KS',
'Kentucky': 'KY',
'Louisiana': 'LA',
'Maine': 'ME',
'Maryland': 'MD',
'Massachusetts': 'MA',
'Michigan': 'MI',
'Minnesota': 'MN',
'Mississippi': 'MS',
'Missouri': 'MO',
'Montana': 'MT',
'Nebraska': 'NE',
'Nevada': 'NV',
'New Hampshire': 'NH',
'New Jersey': 'NJ',
'New Mexico': 'NM',
'New York': 'NY',
'North Carolina': 'NC',
'North Dakota': 'ND',
'Northern Mariana Islands':'MP',
'Ohio': 'OH',
'Oklahoma': 'OK',
'Oregon': 'OR',
'Pennsylvania': 'PA',
'Puerto Rico': 'PR',
'Rhode Island': 'RI',
'South Carolina': 'SC',
'South Dakota': 'SD',
'Tennessee': 'TN',
'Texas': 'TX',
'Utah': 'UT',
'Vermont': 'VT',
'Virgin Islands': 'VI',
'Virginia': 'VA',
'Washington': 'WA',
'Washington DC' : 'DC',
'West Virginia': 'WV',
'Wisconsin': 'WI',
'Wyoming': 'WY'
}
for v in state_abbrevs.values():
t = gtab.GTAB()
t.set_options(pytrends_config={"geo": f"US-{v}", "timeframe": "2020-09-01 2020-10-01"})
query = t.new_query("weather")
I've tried using an f string but that produces SyntaxError: can't assign to literal.

I used two answers from here. I think your best option is just storing the DataFrames in a dictionary but this should work to create your query_* variables.
query_dict = {}
for n, v in enumerate(state_abbrevs.values()):
t = gtab.GTAB()
t.set_options(pytrends_config={"geo": f"US-{v}", "timeframe": "2020-09-01 2020-10-01"})
query = t.new_query("weather")
key = "query_" + str(n)
query_dict[key] = query
for k in query_dict.keys():
exec("%s = query_dict['%s']" % (k,k))

Related

How can I extract values in parentheses from a Python list using a regex?

This is the data as a list:
states = ['Alabama (AL)', 'Alaska (AK)', 'Arizona (AZ)', 'Arkansas (AR)', 'California (CA)', 'Colorado (CO)', 'Connecticut (CT)', 'Delaware (DE)', 'District of Columbia (DC)', 'Florida (FL)', 'Georgia (GA)', 'Hawaii (HI)', 'Idaho (ID)', 'Illinois (IL)', 'Indiana (IN)', 'Iowa (IA)', 'Kansas (KS)', 'Kentucky (KY)', 'Louisiana (LA)', 'Maine (ME)', 'Maryland (MD)', 'Massachusetts (MA)', 'Michigan (MI)', 'Minnesota (MN)', 'Mississippi (MS)', 'Missouri (MO)', 'Montana (MT)', 'Nebraska (NE)', 'Nevada (NV)', 'New Hampshire (NH)', 'New Jersey (NJ)', 'New Mexico (NM)', 'New York (NY)', 'North Carolina (NC)', 'North Dakota (ND)', 'Ohio (OH)', 'Oklahoma (OK)', 'Oregon (OR)', 'Pennsylvania (PA)', 'Rhode Island (RI)', 'South Carolina (SC)', 'South Dakota (SD)', 'Tennessee (TN)', 'Texas (TX)', 'Utah (UT)', 'Vermont (VT)', 'Virginia (VA)', 'Washington (WA)', 'West Virginia (WV)', 'Wisconsin (WI)', 'Wyoming (WY)']
I want to extract all the codes in parentheses.
This code returned None:
re.search('[(A-Z)]')
How can I do this?
Since you're using a list, you probably don't need a regex. If you're guaranteed that's the format, something like this should do it:
abbreviations = [state[-3:-1] for state in states]
That code uses a List Comprehension to make a new list from your old list. For each item in the states list, we're using negative indexes (which start at the back of the string) and the slice operator to pull out the abbreviations since they're always the 2nd to last and 3rd to last characters in the strings.
Sample usage:
>>> states = ['Alabama (AL)', 'Alaska (AK)', 'Arizona (AZ)', 'Arkansas (AR)', 'California (CA)']
>>> [state[-3:-1] for state in states]
['AL', 'AK', 'AZ', 'AR', 'CA']
import re
regex = r"(?<=\()[A-Z]+(?=\))"
print(re.findall(regex, "".join(states)))
Output:
['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY']

How would i go about randomizing the questions for this game? [duplicate]

This question already has answers here:
Shuffling a list of objects
(25 answers)
Closed 5 years ago.
for a homework assignment, i'm trying to make a game that quizzes users on the capitals of each state, kind of like a flashcards game. I've satisfied all requirements for the program with the code below except they want the questions to be in a random order. how can i shuffle the dictionary?
I know how to shuffle a list but not a dictionary, as i thought they were already supposed to be in a random order.. yet i get the questions in the same order i typed the keys/values (alphabetical by state)
flashcards = {'ALABAMA': 'MONTGOMERY',
'ALASKA': 'JENEAU',
'ARIZONA': 'PHOENIX',
'ARKANSAS': 'LITTLE ROCK',
'CALIFORNIA': 'SACRAMENTO',
'COLORADO': 'DENVER',
'CONNECTICUT': 'HARTFORD',
'DELAWARE': 'DOVER',
'FLORIDA': 'TALLAHASSEE',
'GEORGIA': 'ATLANTA',
'HAWAII': 'HONOLULU',
'IDAHO': 'BOISE',
'ILLINOIS': 'SPRINGFIELD',
'INDANA': 'INDIANAPOLIS',
'IOWA': 'DES MOINES',
'KANSAS': 'TOPEKA',
'KENTUCKY': 'FRANKFORT',
'LOUISIANA': 'BATON ROUGE',
'MAINE': 'AUGUSTA',
'MARYLAND': 'ANNAPOLIS',
'MASSACHUSETTS': 'BOSTON',
'MICHIGAN': 'LANSING',
'MINNESOTA': 'ST. PAUL',
'MISSISSIPPI': 'JACKSON',
'MISSOURI': 'JEFFERSON CITY',
'MONTANA': 'HELENA',
'NEBRASKA': 'LINCOLN',
'NAVADA': 'CARSON CITY',
'NEW HAMPSHIRE': 'CONCORD',
'NEW JERSEY': 'TRENTON',
'NEW MEXICO': 'SANTA FE',
'NEW YORK': 'ALBANY',
'NORTH CAROLINA': 'RALEIGH',
'NORTH DAKOTA': 'BISMARCK',
'OHIO': 'COLUMBUS',
'OKLAHOMA': 'OKLAHOMA CITY',
'OREGON': 'SALEM',
'PENNSYLVANIA': 'HARRISBURG',
'RHODE ISLAND': 'PROVIDENCE',
'SOUTH CAROLINA': 'COLUMBIA',
'SOUTH DAKOTA': 'PIERRE',
'TENNESSEE': 'NASHVILLE',
'TEXAS': 'AUSTIN',
'UTAH': 'SALT LAKE CITY',
'VERMONT': 'MONTPELIER',
'VIRGINIA': 'RICHMOND',
'WASHINTON': 'OLYMPIA',
'WEST VIRGINIA': 'CHARLESTON',
'WISCONSIN': 'MADISON',
'WYOMING': 'CHEYENNE'}
def main():
incorrect = 0
correct = 0
print('Let\'s play the State\'s game!!')
for b in flashcards.keys():
question = input('What is the capital of ' + b +'? : ')
if question.upper() == flashcards[b].upper():
correct += 1
print('correct!!')
print('Correct: ', correct)
print('Incorrect: ', incorrect)
else:
incorrect += 1
print('oops! that is incorrect')
print('Correct: ', correct)
print('Incorrect: ', incorrect)
main()
Use random.shuffle
from random import shuffle
states = flashcards.keys()
shuffle(states)
for state in states:
print 'State: {}, Capital: {}'.format(state, flashcards[state])

Why quizfile.write(" ") is not working from the Second for loop

I got this question Automate the boring Stuff book. The Code is also given there but When I was Practising this on my own the problem I am getting is this code is not writing in the files after the first for loop.
import random
import os
capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',
'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver',
'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee',
'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois':
'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas':
'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine':
'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan':
'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri':
'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada':
'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton',
'New Mexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh',
'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City',
'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence',
'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee':
'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont':
'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia',
'West Virginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'}
#print (capitals)
for q in range(35):
quizfile = open("capitalquiz%s.txt" %(q + 1), 'w')
answerfile = open("Answerfile%s.txt"%(q + 1),'w')
quizfile.write('Name:\n\nDate:\n\nPeriod:\n\n')
quizfile.write((' ' * 20) + 'State Capitals Quiz (Form %s)' % (q + 1))
quizfile.write('\n\n')
states = list(capitals.keys())
random.shuffle(states)
quizfile.write("wefkjqennqkeanfeqkjn")
for i in range(50):
correct_answer = capitals[states[i]]
wrong_answer = list(capitals.values())
del wrong_answer[correct_answer.index(correct_answer)]
wrong_answers = random.sample(wrong_answer,3)
answer_option = wrong_answers + [correct_answer]
random.shuffle(answer_option)
for item in range(50):
#quizfile.write("******************************************************")
quizfile.write("%s.what is the capital of %s" %(item+1,states[item]))
for i in range(4):
quizfile.write("%s. %s\n" %('ABCD'[i],answer_option[i]))
answerfile.write("%s. %s\n" %(q+1,'ABCD'[answer_option.index(correct_answer)]))
quizfile.close()
answerfile.close()
You've got some for loops that need to be nested within others. You're attempting to access out of scope variables as it is now.
Your code, cleaned up:
import random
import os
capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',
'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver',
'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee',
'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois':
'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas':
'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine':
'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan':
'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri':
'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada':
'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton',
'New Mexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh',
'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City',
'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence',
'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee':
'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont':
'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia',
'West Virginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'}
for q in range(35):
quizfile = open("capitalquiz%s.txt" %(q + 1), 'w')
answerfile = open("Answerfile%s.txt"%(q + 1),'w')
quizfile.write('Name:\n\nDate:\n\nPeriod:\n\n')
quizfile.write((' ' * 20) + 'State Capitals Quiz (Form %s)' % (q + 1))
quizfile.write('\n\n')
states = list(capitals.keys())
random.shuffle(states)
for i in range(50):
correct_answer = capitals[states[i]]
wrong_answer = list(capitals.values())
del wrong_answer[correct_answer.index(correct_answer)]
wrong_answers = random.sample(wrong_answer,3)
answer_option = wrong_answers + [correct_answer]
random.shuffle(answer_option)
quizfile.write("%s.what is the capital of %s \n" %(i+1,states[i]))
for j in range(4):
quizfile.write("%s. %s\n" %('ABCD'[j],answer_option[j]))
quizfile.write('\n')
answerfile.write("%s. %s\n" %(i+1,'ABCD'[answer_option.index(correct_answer)]))
quizfile.close()
answerfile.close()
It's not the prettiest but I think it does what you're trying to do.

variable in if statement not defined(again)

This is the code that I am having problems with, it only works when there is a state put in. I need it to work when there is a state put in and when a state and a city are put in. Really all I need is someone to help me with the variable.
import urllib2
num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
capitals = {'Alabama': 'Montgomery',
'Alaska': 'Juneau',
'Arizona': 'Phoenix',
'Arkansas': 'Little Rock',
'California': 'Sacramento',
'Colorado': 'Denver',
'Connecticut': 'Hartford',
'Delaware': 'Dover',
'Florida': 'Tallahassee',
'Georgia': 'Atlanta',
'Hawaii': 'Honolulu',
'Idaho': 'Boise',
'Illinois': 'Springfield',
'Indiana': 'Indianapolis',
'Iowa': 'Des Moines',
'Kansas': 'Topeka',
'Kentucky': 'Frankfort',
'Louisiana': 'Baton Rouge',
'Maine': 'Augusta',
'Maryland': 'Annapolis',
'Massachusetts': 'Boston',
'Michigan': 'Lansing',
'Minnesota': 'St. Paul',
'Mississippi': 'Jackson',
'Missouri': 'Jefferson City',
'Montana': 'Helena',
'Nebraska': 'Lincoln',
'Nevada': 'Carson City',
'New Hampshire': 'Concord',
'New Jersey': 'Trenton',
'New Mexico': 'Santa Fe',
'New York': 'Albany',
'North Carolina': 'Raleigh',
'North Dakota': 'Bismark',
'Ohio': 'Columbus',
'Oklahoma': 'Oklahoma City',
'Oregon': 'Salem',
'Pennsylvania': 'Harrisburg',
'Rhode Island': 'Providence',
'South Carolina': 'Columbia',
'South Dakota': 'Pierre',
'Tennessee': 'Nashville',
'Texas': 'Austin',
'Utah': 'Salt Lake City',
'Vermont': 'Montpelier',
'Virgina': 'Richmond',
'Washington': 'Olympia',
'West Virgina': 'Charleston',
'Wisconsin': 'Madison',
'Wyoming': 'Cheyenne'}
states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida',
'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine',
'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska',
'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio',
'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas',
'Utah', 'Vermont', 'Virgina', 'Washington','West Virgina', 'Wisconsin', 'Wyoming']
def make_word(words):
result = ""
for i in words:
result += i
return result
while 1:
a = raw_input('Put in a place: ')
a = a.lower()
y = a.replace(' ', '%20')
a = list(a)
a[0] = a[0].upper()
a = ''.join(a)
num = 0
cap = 0
for key in capitals:
if key == a:
page = urllib2.urlopen('http://woeid.rosselliot.co.nz/lookup/%s' % capitals[key]).read()
cap = capitals[key]
num += 1
if a in states:
f = page.find(cap)
if f != -1:
start = page.find('data-center_long="', f) + 18
end = page.find('"', start)
start1 = page.find('data-center_lat="', end) + 17
end1 = page.find('"', start1)
print '%s Latitude: %s Longitude: %s' % (a, page[start1:end1], page[start:end])
else:
for b in states:
l = len(b) + 1
f = a.find(b)
if f != -1:
f = len(a[f:])
f = len(a) - f
f = a[:f]
page = urllib2.urlopen('http://woeid.rosselliot.co.nz/lookup/%s' % f).read()
start = page.find('data-center_long="', f) + 18
end = page.find('"', start)
start1 = page.find('data-center_lat="', end) + 17
end1 = page.find('"', start1)
print '%s Latitude: %s Longitude: %s' % (a, page[start1:end1], page[start:end])
This says the variable is not defined but I need the code to stay like this or else it most likely won't work. Can someone give me a helpful hint or an answer?
f variable is declared inside if a in states. So, if a in states condition evaluates to False, f will not be defined.

AttributeError: 'NoneType' object has no attribute 'index'

I am trying to make a US Capitals game for my sister, but when I do the following code:
import random
allUSStates = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming']
allUSCapitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix', 'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver', 'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee', 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois': 'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas': 'Topeka', 'Kentucky': 'Frankfurt', 'Louisiana': 'Baton Rouge', 'Maine': 'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan': 'Lansing', 'Minnesota': 'St. Paul', 'Mississippi': 'Jackson', 'Missouri': 'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada': 'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton', 'New Mexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh', 'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma', 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence', 'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee': 'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont': 'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia', 'West Virginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'}
states = allUSStates
numwrong = 0
while len(states) > 0:
state = random.choice(states)
capital = allUSCapitals[random.choice(states)]
print('What is the capital of %s?' % state)
choice1 = allUSCapitals[state]
choice2 = choice1
choice3 = choice1
while choice2 == choice1 or choice3 == choice1 or choice2 == choice3:
choice2 = allUSCapitals[random.choice(allUSStates)]
choice3 = allUSCapitals[random.choice(allUSStates)]
allChoices = [choice1, choice2, choice3]
allChoices = random.shuffle(allChoices)
correctAnswer = allChoices.index(choice1)
print(' 1. ' + allChoices[0] + ' \n 2. ' + allChoices[1] + ' \n 3. ' + allChoices[2] + ' \n')
answer = int(float(input())) - 1
if answer == correctAnswer:
print('\nGood job!')
else:
print('Nope! The answer is ' + choice1 + '!')
numwrong += 1
del states[states.index(choice1)]
percentwrong = (numwrong/50)*100
print('\n\n\n\nYou got ' + numwrong + ' wrong out of 50, or ' + percentwrong + '% wrong.')
I get this error:
Traceback (most recent call last):
File "C:\Python32\USStates.py", line 18, in module
correctAnswer = allChoices.index(choice1)
AttributeError: 'NoneType' object has no attribute 'index'
What does this mean and what can I do to fix this?
Python is trying to tell you that when you got to line 18, allChoices is None and None objects don't have an index method. The reason for this is because random.shuffle shuffles the list in place and returns None.
The fix is to change:
allChoices = random.shuffle(allChoices)
to:
random.shuffle(allChoices)

Categories

Resources