I’m don’t have the knowledge, but ChatGPT does…

I’m work­ing on a web­site, build­ing pages that have ran­dom pull-quotes on them. And I’m mak­ing mockup / place­hold­er pages.

Many mockups. This gets old pretty quickly so I’m think­ing 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 min­ion to see if they were up to the task. Here’re the require­ments I had:

  • quote from sci­ence fic­tion, or by a sci­ence fic­tion author
  • repeat­able without enga­ging Chat­G­PT every time I needed a quote
  • ran­dom, sur­prise me every time
  • attrib­ute the quote to the author and if known, the media (movie, TV, etc)
  • save the quotes to a text file

Well, as you can ima­gine, there was a bit of back and forth between myself and Chat­G­PT, but in the end, it turned out they gen­er­ated a Python script for me that accom­plishes my needs.

Here’s a sample of the output:

1. “The last ever dol­phin mes­sage was mis­in­ter­preted as a sur­pris­ingly soph­ist­ic­ated attempt to do a double-back­wards-somer­sault through a hoop whilst whist­ling the ‘Star Spangled Ban­ner’, but in fact the mes­sage was this: So long and thanks for all the fish.” — Douglas Adams, The Hitch­hiker­’s Guide to the Galaxy
2. “I have nev­er listened to any­one who cri­ti­cized my taste in space travel, sideshows or gor­il­las. When this occurs, I pack up my dino­saurs and leave the room.” — Ray Brad­bury, Zen in the Art of Writing
3. “You’re not a Quaker, Jeremy. I hap­pen to know you put beer on your corn­flakes.” — Kyle Keyes, Match­ing Configurations
4. “I guess I always felt even if the world came to an end, McDon­ald’s would still be open.” — Susan Pfef­fer, Life As We Knew It

It’s Alive!

Seems that’ll do for what I need. All I have to do whenev­er I need one is just invoke the python script below, which will dump the out­put to the con­sole as well as to a date stamped text file.

As you can see from the prompts below, I spe­cified ‘sci­ence fic­tion char­ac­ters’, but I could have just as eas­ily said ‘fam­ous sleuths and invest­ig­at­ors from lit­er­at­ure and film’ and would have appro­pri­ate results.

In my case, it’s pulling from Goodreads, but with a dif­fer­ent prompt, the res­ult could have come from anoth­er source.

So, without fur­ther adieu, here’re the prompts I used to gen­er­ate the Python code. I’ve removed their replies for brev­ity. You’ll notice I’m rather friendly and con­ver­sa­tion­al with the applic­a­tion — polite­ness nev­er 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.

Chat­G­PT assures me that by repeat­ing 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
            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}'
                # This is a quote from a real person or a book
                quote_text += f' - {attribution}'
    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:
        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(f"Output written to {file_name}")

Why? Well why not!

With just a little bit of con­ver­sa­tion and think­ing about what I needed done (ran­dom quotes gen­er­ated), I got a python script back that can reli­ably get those quotes from an online source. Faster than I could manu­ally do it. And it was kinda fun to con­verse with the lan­guage mod­el to see how it would apply what they thought my inten­tion was.



, , , , ,




Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.