Created
October 10, 2025 09:46
-
-
Save ostechnix/c6e47366a41d1ef6f9d3e994412c4299 to your computer and use it in GitHub Desktop.
NobelCLI: A Python Script to Fetch and Display Nobel Prize Winners in Terminal using the Official Nobel Prize API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # ------------------------------------------------------------------ | |
| # Script Name: NobelCLI | |
| # Description: Fetches and displays Nobel Prize winners | |
| # in a formatted terminal output | |
| # Website: https://gist.github.com/ostechnix | |
| # ------------------------------------------------------------------ | |
| import json | |
| import sys | |
| import argparse | |
| from datetime import datetime | |
| from urllib.request import urlopen, Request | |
| from urllib.error import URLError, HTTPError | |
| def fetch_nobel_prizes(year=None, category=None): | |
| """Fetch Nobel Prize data from the official API""" | |
| base_url = "https://api.nobelprize.org/2.1/nobelPrizes" | |
| params = [] | |
| if year: | |
| params.append(f"nobelPrizeYear={year}") | |
| if category: | |
| # Map category names to API format | |
| category_map = { | |
| 'physics': 'phy', | |
| 'chemistry': 'che', | |
| 'medicine': 'med', | |
| 'literature': 'lit', | |
| 'peace': 'pea', | |
| 'economics': 'eco' | |
| } | |
| params.append(f"nobelPrizeCategory={category_map.get(category, category)}") | |
| url = base_url + ("?" + "&".join(params) if params else "") | |
| try: | |
| req = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) | |
| with urlopen(req) as response: | |
| return json.loads(response.read().decode()) | |
| except (URLError, HTTPError) as e: | |
| print(f"Error fetching data: {e}", file=sys.stderr) | |
| print("\nPossible causes:", file=sys.stderr) | |
| print(" - No internet connection", file=sys.stderr) | |
| print(" - Nobel Prize API is temporarily unavailable", file=sys.stderr) | |
| print(" - Firewall or network restrictions", file=sys.stderr) | |
| sys.exit(1) | |
| def format_laureate(laureate): | |
| """Format laureate information""" | |
| name = laureate.get('knownName', {}).get('en', 'Unknown') | |
| org_name = laureate.get('orgName', {}).get('en', '') | |
| if org_name: | |
| return org_name | |
| return name | |
| def display_prizes(data, year=None, category=None): | |
| """Display Nobel Prizes in a formatted way""" | |
| prizes = data.get('nobelPrizes', []) | |
| if not prizes: | |
| print("\n" + "="*80) | |
| print(f"{'NO RESULTS FOUND':^80}") | |
| print("="*80 + "\n") | |
| # Provide helpful error messages based on the input | |
| if year and year < 1901: | |
| print(f"❌ The Nobel Prizes were first awarded in 1901, not {year}.") | |
| print(f" Please specify a year from 1901 onwards.\n") | |
| elif year and year > datetime.now().year: | |
| print(f"❌ The year {year} is in the future.") | |
| print(f" Please specify a year up to {datetime.now().year}.\n") | |
| elif year and category: | |
| print(f"❌ No {category.capitalize()} prize was awarded in {year}.") | |
| print(f" This may happen during war years or other special circumstances.") | |
| print(f" Try checking other years or categories.\n") | |
| elif year: | |
| print(f"❌ No Nobel Prizes were awarded in {year}.") | |
| print(f" This is unusual - please verify the year.\n") | |
| elif category: | |
| print(f"❌ No {category.capitalize()} prizes found matching your criteria.") | |
| print(f" Try a different year range or check the spelling.\n") | |
| else: | |
| print("❌ No Nobel Prizes found for the specified criteria.") | |
| print(" Please try different search parameters.\n") | |
| return | |
| print("\n" + "="*80) | |
| print(f"{'NOBEL PRIZES':^80}") | |
| print("="*80 + "\n") | |
| for prize in prizes: | |
| prize_year = prize.get('awardYear', 'Unknown') | |
| prize_category = prize.get('category', {}).get('en', 'Unknown') | |
| print(f"┌─ {prize_year} - {prize_category.upper()}") | |
| print("│") | |
| # Handle prizes with laureates | |
| laureates = prize.get('laureates', []) | |
| if laureates: | |
| for i, laureate in enumerate(laureates, 1): | |
| name = format_laureate(laureate) | |
| motivation = laureate.get('motivation', {}).get('en', '') | |
| prefix = "├─" if i < len(laureates) else "└─" | |
| print(f"{prefix} {name}") | |
| if motivation: | |
| # Clean up motivation text | |
| motivation = motivation.strip('"') | |
| # Wrap long motivations | |
| max_width = 72 | |
| words = motivation.split() | |
| lines = [] | |
| current_line = [] | |
| current_length = 0 | |
| for word in words: | |
| if current_length + len(word) + 1 <= max_width: | |
| current_line.append(word) | |
| current_length += len(word) + 1 | |
| else: | |
| lines.append(' '.join(current_line)) | |
| current_line = [word] | |
| current_length = len(word) | |
| if current_line: | |
| lines.append(' '.join(current_line)) | |
| indent = "│ " if i < len(laureates) else " " | |
| for line in lines: | |
| print(f"{indent} {line}") | |
| else: | |
| print("└─ No prize awarded this year") | |
| print() | |
| # Print verification link at the end | |
| print("="*80) | |
| if year: | |
| print(f"Verify official page: https://www.nobelprize.org/all-nobel-prizes-{year}/") | |
| else: | |
| print("Verify official page: https://www.nobelprize.org/prizes/") | |
| print("="*80 + "\n") | |
| def main(): | |
| parser = argparse.ArgumentParser( | |
| description='View Nobel Prize winners in the terminal', | |
| formatter_class=argparse.RawDescriptionHelpFormatter, | |
| epilog=""" | |
| Examples: | |
| %(prog)s --year 2024 | |
| %(prog)s --year 2023 --category physics | |
| %(prog)s --category chemistry | |
| Available categories: | |
| physics, chemistry, medicine, literature, peace, economics | |
| Note: Nobel Prizes have been awarded since 1901. | |
| """ | |
| ) | |
| parser.add_argument('-y', '--year', type=int, | |
| help='Filter by year (e.g., 2024)') | |
| parser.add_argument('-c', '--category', | |
| choices=['physics', 'chemistry', 'medicine', | |
| 'literature', 'peace', 'economics'], | |
| help='Filter by category') | |
| args = parser.parse_args() | |
| # Validate year range | |
| current_year = datetime.now().year | |
| if args.year: | |
| if args.year < 1901: | |
| print(f"❌ Error: Nobel Prizes were first awarded in 1901.", file=sys.stderr) | |
| print(f" You specified: {args.year}", file=sys.stderr) | |
| print(f" Please use a year from 1901 to {current_year}.\n", file=sys.stderr) | |
| sys.exit(1) | |
| elif args.year > current_year: | |
| print(f"❌ Error: The year {args.year} is in the future.", file=sys.stderr) | |
| print(f" Current year is {current_year}.", file=sys.stderr) | |
| print(f" Please use a year from 1901 to {current_year}.\n", file=sys.stderr) | |
| sys.exit(1) | |
| # Fetch and display | |
| data = fetch_nobel_prizes(args.year, args.category) | |
| display_prizes(data, args.year, args.category) | |
| if __name__ == '__main__': | |
| main() |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NobelCLI - Fetch Nobel Prize Winners from Your Terminal
Overview
NobelCLI is a lightweight Python script that fetches Nobel Prize winners directly from your Linux terminal using the official Nobel Prize API.
It allows you to filter results by year and category (Physics, Chemistry, Literature, Peace, Economics, Medicine, etc.) without leaving the command line.
Installation
Using
curlOr using
wgetAdd to PATH (if needed)
Check if
~/.local/binis in your PATH:If it’s missing, add:
to your
~/.bashrcor~/.zshrc, then reload:Usage Examples
🔗 GitHub Gist Link
https://gist.github.com/ostechnix/c6e47366a41d1ef6f9d3e994412c4299