Skip to content

Instantly share code, notes, and snippets.

@scottstanie
Created July 8, 2024 14:34
Show Gist options
  • Save scottstanie/2f23ac4ab457e2eac3b02195f982fcc3 to your computer and use it in GitHub Desktop.
Save scottstanie/2f23ac4ab457e2eac3b02195f982fcc3 to your computer and use it in GitHub Desktop.
Print a random chapter from Ursula Le Guin's Tao
import requests
import re
import random
from rich.console import Console
from rich.panel import Panel
from rich.text import Text
url = "https://raw.githubusercontent.com/nrrb/tao-te-ching/master/Ursula%20K%20Le%20Guin.md"
def get_random_chapter():
response = requests.get(url)
if response.status_code == 200:
content = response.text
# Split the content into chapters
chapters = re.split(r'# \d+', content)[1:] # Skip the first split which is the intro
if chapters:
# Select a random chapter
random_chapter = random.choice(chapters)
# Extract chapter number and title
chapter_info = re.match(r'\n## (.+)\n', random_chapter)
if chapter_info:
chapter_title = chapter_info.group(1)
chapter_content = random_chapter[chapter_info.end():]
# Remove any trailing sections (like notes)
chapter_content = re.split(r'\n>', chapter_content)[0]
return chapter_title, chapter_content.strip()
return None, None
else:
return None, None
console = Console()
chapter_title, chapter_content = get_random_chapter()
if chapter_title and chapter_content:
title = Text(f"Chapter: {chapter_title}", style="bold magenta")
content = Text(chapter_content)
panel = Panel(content, title=title, expand=False, border_style="green")
console.print(panel)
else:
console.print("Failed to fetch or parse content", style="bold red")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment