You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python名言记忆程序开发求助:实现书籍/角色名言测试及All_AIC功能

Got it, let's walk through building this Python quote memorization tool step by step. I’ll break down the core components with actionable code snippets and tips to match your requirements:

1. Data Structure & Storage

First, we need a clean way to store quotes with book and character metadata. A JSON file works perfectly here—it’s human-readable and easy to parse in Python. Here’s an example structure:

{
  "books": [
    {
      "title": "To Kill a Mockingbird",
      "quotes": [
        {"character": "Atticus Finch", "text": "You never really understand a person until you consider things from his point of view… until you climb into his skin and walk around in it."},
        {"character": "Scout Finch", "text": "Until I feared I would lose it, I never loved to read. One does not love breathing."}
      ]
    },
    {
      "title": "1984",
      "quotes": [
        {"character": "Winston Smith", "text": "Big Brother is watching you."},
        {"character": "O'Brien", "text": "Power is not a means, it is an end."}
      ]
    }
  ]
}

Save this as quotes.json—we’ll reference it in our code.

2. Mode Selection Logic

Let’s build a simple prompt to let users pick their test mode, with validation to ensure they enter a valid choice:

def select_test_mode():
    print("=== Quote Memorization Test ===")
    print("Choose your test type:")
    print("1. Memorize all quotes from a specific book")
    print("2. Memorize quotes from a specific character")
    
    while True:
        user_choice = input("\nEnter 1 or 2: ").strip()
        if user_choice in ["1", "2"]:
            return int(user_choice)
        print("Oops, that's not a valid option. Try again with 1 or 2.")
3. Load & Filter Quotes

Next, we need to load the JSON data and filter it based on the user’s selected mode. This function will return only the quotes relevant to their test:

import json

def load_quotes(file_path="quotes.json"):
    try:
        with open(file_path, "r", encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"Error: Couldn't find {file_path}. Make sure the file exists in the same folder.")
        return {"books": []}

def filter_target_quotes(quotes_data, mode):
    target_quotes = []
    if mode == 1:
        book_title = input("Enter the book title: ").strip().lower()
        for book in quotes_data["books"]:
            if book["title"].lower() == book_title:
                target_quotes = [quote["text"] for quote in book["quotes"]]
                break
        if not target_quotes:
            print(f"No quotes found for '{book_title}'.")
    elif mode == 2:
        character_name = input("Enter the character's name: ").strip().lower()
        for book in quotes_data["books"]:
            target_quotes.extend([quote["text"] for quote in book["quotes"] if quote["character"].lower() == character_name])
        if not target_quotes:
            print(f"No quotes found for '{character_name}'.")
    return target_quotes
4. Run the Test & Calculate Score

Now the core test logic: let users input quotes, check if they match the target list, and track their score. We’ll let them type done when they’re finished:

def run_memorization_test(target_quotes):
    if not target_quotes:
        print("No quotes to test. Exiting.")
        return
    
    correct_matches = 0
    remaining_quotes = target_quotes.copy()
    
    print("\nStart entering quotes you remember (type 'done' to finish):")
    while True:
        user_input = input("> ").strip()
        if user_input.lower() == "done":
            break
        if user_input in remaining_quotes:
            print("✅ Correct!")
            correct_matches += 1
            remaining_quotes.remove(user_input)
        else:
            print("❌ That quote isn't in the target list. Try again.")
    
    total_quotes = len(target_quotes)
    score = (correct_matches / total_quotes) * 100 if total_quotes > 0 else 0
    print(f"\n=== Test Results ===")
    print(f"You remembered {correct_matches} out of {total_quotes} quotes.")
    print(f"Your score: {score:.2f}%")
5. Tie It All Together with a Main Function

Finally, we’ll create a main function to run the entire workflow:

def main():
    quotes_data = load_quotes()
    test_mode = select_test_mode()
    target_quotes = filter_target_quotes(quotes_data, test_mode)
    run_memorization_test(target_quotes)

if __name__ == "__main__":
    main()
Bonus Improvements (Optional)
  • Fuzzy Matching: Use the difflib library to accept close matches instead of exact text (great for typos).
  • Progress Tracking: Show how many quotes are left to remember as the user inputs them.
  • Multiple Files: Add support for loading quotes from multiple JSON/CSV files to expand your library easily.

内容的提问来源于stack exchange,提问作者Luca J C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:24:11