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

Python实现JSON存储笑话的关键词搜索功能求助

Solution for Joke Catalogue Search Functionality

Hey there! I see you're building a joke catalogue and need help filling in the empty [s]earch branch. Let's get that search feature working so users can find jokes by keywords easily. Here's how to implement it:

Step-by-Step Breakdown

  1. Gather matching jokes: Loop through every joke in your data_list and check if the search term appears in either the joke's setup or punchline.
  2. Add case insensitivity (optional but user-friendly): Convert both the search term and joke text to lowercase so searches like "dog" will match "Dog" or "DOG" too—no need for users to worry about capitalization.
  3. Display results clearly: If we find matches, print each joke with its setup and punchline. If no matches exist, show the required "No jokes match the search term" message.

Filled-in [s]earch Branch Code

Here's the complete code for the search section that you can drop right into your existing program:

elif choice == 's':
    search_term = input_something('Enter search term: ')
    # Normalize to lowercase for case-insensitive search
    lower_search = search_term.lower()
    matching_jokes = []
    
    # Check each joke for the search term
    for joke in data_list:
        if (lower_search in joke['setup'].lower() 
            or lower_search in joke['punchline'].lower()):
            matching_jokes.append(joke)
    
    # Handle results
    if matching_jokes:
        print(f"\nFound {len(matching_jokes)} matching joke(s):")
        for idx, joke in enumerate(matching_jokes, 1):
            print(f"\nJoke {idx}:")
            print(f"Setup: {joke['setup']}")
            print(f"Punchline: {joke['punchline']}")
    else:
        print('No jokes match the search term')

Small Fixes to Your Original Code

While I was at it, I cleaned up a couple of minor issues to make your code more robust:

  • Fixed the input_something function to use an else clause instead of redundant if checks, so it exits the loop as soon as valid input is received.
  • Updated the exception handling to catch all errors and print a meaningful message (instead of just TypeError, which won't cover cases like the data.txt file being missing).
  • Added .lower() to the choice input so users can type uppercase letters (like 'S') and still trigger the search.

Full Updated Program (for context)

Here's how your complete loop section will look with the search feature added:

import json
def input_something(enter_message):
    while True:
        inputSomething = input(enter_message)
        if len(inputSomething) < 1:
            print("Invalid Input - Enter Something.")
        else:
            return inputSomething

data_list = []
try:
    with open('data.txt') as openfile:
        data_list = json.load(openfile)
except Exception as e:
    print(f"Error loading joke data: {e}")

print('Welcome to the Joke Catalogue Admin Program.')
while True:
    print('\nChoose [a]dd, [l]ist, [s]earch, [v]iew, [d]elete or [q]uit.')
    choice = input('> ').lower()
    
    if choice == 'a':
        # Add your joke creation logic here
        pass
    elif choice == 'l':
        # Add your full joke list logic here
        pass
    elif choice == 's':
        search_term = input_something('Enter search term: ')
        lower_search = search_term.lower()
        matching_jokes = []
        
        for joke in data_list:
            if (lower_search in joke['setup'].lower() 
                or lower_search in joke['punchline'].lower()):
                matching_jokes.append(joke)
        
        if matching_jokes:
            print(f"\nFound {len(matching_jokes)} matching joke(s):")
            for idx, joke in enumerate(matching_jokes, 1):
                print(f"\nJoke {idx}:")
                print(f"Setup: {joke['setup']}")
                print(f"Punchline: {joke['punchline']}")
        else:
            print('No jokes match the search term')
    elif choice == 'v':
        # Add your single joke view logic here
        pass
    elif choice == 'd':
        # Add your joke deletion logic here
        pass
    elif choice == 'q':
        print('Quitting joke bot! See you next time!')
        break
    else:
        print("Invalid choice - Please only select from the options provided!")

内容的提问来源于stack exchange,提问作者Nigel Wash

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 16:02:47