I’m working on a website, building pages that have random pull-quotes on them. And I’m making mockup / placeholder pages.
Many mockups. This gets old pretty quickly so I’m thinking to myself, “Self? Let’s see if we can have some fun with these quotes”.
But, rather than just do a search for quotes, I thought I’d try and deploy my mighty machine-learn-ed minion to see if they were up to the task. Here’re the requirements I had:
- quote from science fiction, or by a science fiction author
- repeatable without engaging ChatGPT every time I needed a quote
- random, surprise me every time
- attribute the quote to the author and if known, the media (movie, TV, etc)
- save the quotes to a text file
Well, as you can imagine, there was a bit of back and forth between myself and ChatGPT, but in the end, it turned out they generated a Python script for me that accomplishes my needs.
Here’s a sample of the output:
1. “The last ever dolphin message was misinterpreted as a surprisingly sophisticated attempt to do a double-backwards-somersault through a hoop whilst whistling the ‘Star Spangled Banner’, but in fact the message was this: So long and thanks for all the fish.” — Douglas Adams, The Hitchhiker’s Guide to the Galaxy
2. “I have never listened to anyone who criticized my taste in space travel, sideshows or gorillas. When this occurs, I pack up my dinosaurs and leave the room.” — Ray Bradbury, Zen in the Art of Writing
3. “You’re not a Quaker, Jeremy. I happen to know you put beer on your cornflakes.” — Kyle Keyes, Matching Configurations
4. “I guess I always felt even if the world came to an end, McDonald’s would still be open.” — Susan Pfeffer, Life As We Knew It
It’s Alive!
Seems that’ll do for what I need. All I have to do whenever I need one is just invoke the python script below, which will dump the output to the console as well as to a date stamped text file.
As you can see from the prompts below, I specified ‘science fiction characters’, but I could have just as easily said ‘famous sleuths and investigators from literature and film’ and would have appropriate results.
In my case, it’s pulling from Goodreads, but with a different prompt, the result could have come from another source.
So, without further adieu, here’re the prompts I used to generate the Python code. I’ve removed their replies for brevity. You’ll notice I’m rather friendly and conversational with the application — politeness never hurts:
Prompt 1: Can you create a Python script that will search the internet and generate a short list of memorable quotes from science fiction characters?
Prompt 2: Ok, let's select another source. Also, have the code prompt me for a number of quotes to find.
Prompt 3: Hmm, that source didn't work, do you have another?
Prompt 4: Excellent. that works nicely! Now have each quote also include the story or source media attributed. Also, have the script put the output in a file named 'sf-out.txt' as well as output to the console.
Prompt 5: Ok, update that script to randomize the quotes. Currently it's always pulling the same quote in the same sequence. And have the filename created append the current date and time to the filename before the period and filetype extension.
Prompt 6: Ok, now have the script loop back to the beginning when it completes. This time, pick random quotes from the website, rather than randomizing the order of the results.
Prompt 7: Very nice! Ok, now in the output, if a fictional character says the quote, include the character name in the attribution before the author attribution.
ChatGPT assures me that by repeating those prompts, I’ll get this Python code at the end:
import requests
from bs4 import BeautifulSoup
import random
import datetime
def get_quotes_from_website(url, num_quotes):
"""
Extracts random memorable quotes from a website
"""
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
quotes = []
all_quotes = soup.find_all('div', class_='quoteText')
while len(quotes) < num_quotes:
quote = random.choice(all_quotes)
quote_text = quote.get_text().strip()
quote_text = quote_text.replace('\n', '')
quote_text_parts = quote_text.split('―')
if len(quote_text_parts) > 1:
quote_text = quote_text_parts[0].strip()
attribution = quote_text_parts[1].strip()
if attribution.startswith(','):
# Skip quotes with an invalid attribution
continue
if 'said' in attribution:
# This is a quote from a fictional character
character_name, author_name = attribution.split('said', 1)
character_name = character_name.strip()
author_name = author_name.strip()
quote_text += f' - {character_name}, {author_name}'
else:
# This is a quote from a real person or a book
quote_text += f' - {attribution}'
quotes.append(quote_text)
return quotes
if __name__ == '__main__':
url = 'https://www.goodreads.com/quotes/tag/science-fiction'
while True:
num_quotes = int(input('Enter the number of quotes to generate (or enter 0 to quit): '))
if num_quotes == 0:
break
quotes = get_quotes_from_website(url, num_quotes)
now = datetime.datetime.now()
file_name = f"sf-out-{now.strftime('%Y-%m-%d-%H-%M-%S')}.txt"
with open(file_name, 'w', encoding='utf-8') as file:
file.write(f'Here are {num_quotes} random memorable quotes from science fiction:\n\n')
for i, quote in enumerate(quotes):
quote_line = f"{i+1}. {quote}"
file.write(quote_line + '\n')
print(quote_line)
print(f"Output written to {file_name}")
Why? Well why not!
With just a little bit of conversation and thinking about what I needed done (random quotes generated), I got a python script back that can reliably get those quotes from an online source. Faster than I could manually do it. And it was kinda fun to converse with the language model to see how it would apply what they thought my intention was.
Leave a Reply