Create your own version of the Mayoral Excuse Machine in Python that takes in a name and location, selects an excuse at random and prints an excuse (“Sorry, Richard, I was late to City Hall to meet you, I had a very rough night and woke up sluggish”). Use the “excuses.csv” in the Github repository.
Extra credit if you print the link to the story as well
In [1]:
user_input1 = input("What's the name of the person you were supposed to meet? ")
In [3]:
user_input2 = input("Where were you supposed to go? ")
In [41]:
inputs = {
'name': user_input1,
'place': user_input2
}
In [42]:
inputs
Out[42]:
In [20]:
conn.rollback()
In [17]:
#CSV into Database
import pg8000
excuses = []
conn = pg8000.connect(user='postgres', password='password', database='mayor')
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE mayor_excuses (
excuse varchar(150),
headline varchar(150),
hyperlink varchar(150)
)
""")
conn.commit()
In [18]:
cursor.execute("COPY mayor_excuses(excuse,headline,hyperlink) FROM '/Users/Radhika/Downloads/Lede/12julylede/excuse.csv' DELIMITER ',' CSV")
conn.commit()
In [23]:
import pg8000
m_excuse = []
conn = pg8000.connect(user='postgres', password='password', database='mayor')
cursor = conn.cursor()
cursor.execute("SELECT excuse,headline,hyperlink FROM mayor_excuses")
for row in cursor.fetchall():
dict_exc = {'excuse': row[0], 'headline':row[1], 'hyperline': row[2]}
m_excuse.append(dict_exc)
len(m_excuse)
Out[23]:
In [24]:
m_excuse
Out[24]:
In [58]:
#tried without defining a fun to test it
#import random
#randomz = random.choice(m_excuse)
#possible_keys = [v for k,v in randomz.items() if k=='excuse']
#col = random.choice(possible_keys)
In [59]:
# randomly picking up an excuse from the database, mayor.
import random
def random_excuse(string_in):
randomz = random.choice(m_excuse)
possible_keys = [v for k,v in randomz.items() if k=='excuse']
col = random.choice(possible_keys)
return col
In [60]:
random_excuse(m_excuse)
Out[60]:
In [36]:
#sentence = 'Sorry', user_input1, 'I was late to', user_input2, 'to meet you, because',col
In [66]:
sentence = 'Sorry {} I was late to {} to meet you, because {}. See the news: {}'
In [67]:
output = sentence.format(inputs['name'], inputs['place'], random_excuse(m_excuse), randomz['hyperline'])
In [68]:
print(output)
In [ ]: