Home » Fun Fact Generator which uses a csv file for the facts

Fun Fact Generator which uses a csv file for the facts

Java SE 11 Programmer II [1Z0-816] Practice Tests
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]
Spring Framework Basics Video Course
1 Year Subscription
Oracle Java Certification

To create a Fun Fact Generator that uses a CSV file for storing and retrieving facts, we will read the facts from the CSV file, randomly select one fact, and display it.

The CSV file will contain the facts in a simple format, with each row representing a different fact.

Let’s break this down step by step:

Step 1: Prepare the CSV File

First, create a CSV file (e.g., fun_facts.csv) where each row contains one fun fact. The file structure will look like this:

Honey never spoils. Archaeologists have found pots of honey in ancient Egyptian tombs that are over 3,000 years old and still edible!
A day on Venus is longer than a year on Venus.
Bananas are berries, but strawberries aren't.
There are more stars in the universe than grains of sand on all of Earth's beaches.
Octopuses have three hearts and blue blood.
The Eiffel Tower can be 15 cm taller during the summer due to thermal expansion.
Humans share about 60% of their DNA with bananas.

Save this file as fun_facts.csv in the same directory as your Python script.

Step 2: Import Required Modules

We will need the following modules:

  • csv: To read the fun facts from the CSV file.
  • random: To randomly select a fact from the list.
  • tkinter: To create the GUI (optional, for the GUI version).
import csv
import random
import tkinter as tk  # Optional: for the GUI version

Step 3: Read Facts from the CSV File

We will define a function to read the facts from the CSV file and store them in a list.

# Function to load facts from a CSV file
def load_facts_from_csv(filename):
    facts = []
    with open(filename, newline='', encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            facts.append(row[0])  # Each row contains one fact
    return facts

Explanation:

  • csv.reader() is used to read the rows from the CSV file.
  • Each row contains one fun fact, which is appended to the facts list.
  • The function returns the complete list of fun facts.

Step 4: Create a Function to Generate a Random Fact

We will use the random.choice() method to select a random fact from the list of facts loaded from the CSV file.

# Function to return a random fun fact from the list
def get_random_fact(facts):
    return random.choice(facts)

Explanation:

  • random.choice(facts) randomly selects one fact from the facts list and returns it.

Step 5: Command-Line Version of the Fun Fact Generator

We will now create a simple command-line version of the Fun Fact Generator that prints a random fact when the program runs.

if __name__ == "__main__":
    facts = load_facts_from_csv("fun_facts.csv")  # Load facts from the CSV file
    print("Here is your fun fact for today:")
    print(get_random_fact(facts))  # Print a random fact

Example Output:

Here is your fun fact for today:
Bananas are berries, but strawberries aren't.

Step 6: GUI Version Using Tkinter (Optional)

If you'd like to create a graphical version of the Fun Fact Generator, we can use Tkinter to build a window with a button that generates a new fact when clicked.

Complete Code for the Fun Fact Generator with CSV and Tkinter:

import csv
import random
import tkinter as tk

# Function to load facts from a CSV file
def load_facts_from_csv(filename):
    facts = []
    with open(filename, newline='', encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            facts.append(row[0])  # Each row contains one fact
    return facts

# Function to return a random fun fact from the list
def get_random_fact(facts):
    return random.choice(facts)

# Function to display the fact in the label
def show_fact():
    fact = get_random_fact(facts)
    fact_label.config(text=fact)

# Load the facts from the CSV file
facts = load_facts_from_csv("fun_facts.csv")

# Create the main Tkinter window
root = tk.Tk()
root.title("Fun Fact Generator")
root.geometry("500x300")  # Set the window size

# Create a label to display the fun fact
fact_label = tk.Label(root, text="Click the button for a fun fact!", wraplength=400, font=("Arial", 12), pady=20)
fact_label.pack(pady=20)

# Create a button to generate a new fun fact
fact_button = tk.Button(root, text="Generate Fun Fact", command=show_fact, font=("Arial", 14), bg="lightblue")
fact_button.pack(pady=20)

# Start the Tkinter main loop
root.mainloop()

Explanation:

  1. Main Window:
    • We create the Tkinter window using tk.Tk() and set its size with root.geometry().
  2. Label Widget:
    • The Label widget displays the fun fact. Initially, it shows a placeholder message (“Click the button for a fun fact!”).
    • wraplength=400 ensures that the text wraps within the label for long facts.
  3. Button Widget:
    • The Button widget generates a new fun fact when clicked. It calls the show_fact() function, which updates the text of the label with a new random fact from the CSV file.
  4. Loading Facts from CSV:
    • The facts list is populated by reading from the fun_facts.csv file using the load_facts_from_csv() function.
  5. Event Loop:
    • root.mainloop() starts the Tkinter event loop to keep the window open and interactive, allowing the user to click the button to generate new facts.

Complete Code for Both Versions

Command-Line Version:

import csv
import random

# Function to load facts from a CSV file
def load_facts_from_csv(filename):
    facts = []
    with open(filename, newline='', encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            facts.append(row[0])  # Each row contains one fact
    return facts

# Function to return a random fun fact from the list
def get_random_fact(facts):
    return random.choice(facts)

if __name__ == "__main__":
    facts = load_facts_from_csv("fun_facts.csv")  # Load facts from the CSV file
    print("Here is your fun fact for today:")
    print(get_random_fact(facts))  # Print a random fact

GUI Version with Tkinter:

import csv
import random
import tkinter as tk

# Function to load facts from a CSV file
def load_facts_from_csv(filename):
    facts = []
    with open(filename, newline='', encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            facts.append(row[0])  # Each row contains one fact
    return facts

# Function to return a random fun fact from the list
def get_random_fact(facts):
    return random.choice(facts)

# Function to display the fact in the label
def show_fact():
    fact = get_random_fact(facts)
    fact_label.config(text=fact)

# Load the facts from the CSV file
facts = load_facts_from_csv("fun_facts.csv")

# Create the main Tkinter window
root = tk.Tk()
root.title("Fun Fact Generator")
root.geometry("500x300")  # Set the window size

# Create a label to display the fun fact
fact_label = tk.Label(root, text="Click the button for a fun fact!", wraplength=400, font=("Arial", 12), pady=20)
fact_label.pack(pady=20)

# Create a button to generate a new fun fact
fact_button = tk.Button(root, text="Generate Fun Fact", command=show_fact, font=("Arial", 14), bg="lightblue")
fact_button.pack(pady=20)

# Start the Tkinter main loop
root.mainloop()

Conclusion

In this tutorial, we built a Fun Fact Generator that reads fun facts from a CSV file. We explored:

  • A command-line version, where a random fact is printed when the program is run.
  • A GUI version using Tkinter, where the user can click a button to generate new fun facts from the CSV file.

The CSV approach makes it easy to add or modify facts without changing the code.

This project can be extended by allowing users to load different CSV files or by adding more features, such as categories of facts.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More