如何用Python 3实现用户输入关键词搜索?(自学编程求助)
Hey there! Awesome to see you diving into Python at 15—self-teaching is such a valuable skill to build, keep it up! 😊
Let's break down your need clearly: we want to take user input, check if it contains any of our pre-set keywords, and print a message when a match is found. Here's a straightforward, beginner-friendly implementation:
Basic Version Code
# Define your keyword list—add all the terms you want to match here greetings = ['hi', 'hello', 'hey', 'hi there', 'Hello', 'Hey', 'Hi'] # Get input from the user user_input = input("Enter your text: ") # Check if any keyword exists in the input for keyword in greetings: if keyword in user_input: print("Matched a greeting keyword!") # Add a break if you want to stop checking after the first match break else: # Runs only if no matches were found in the loop print("No preset keywords matched your input.")
Quick Upgrade for Case Insensitivity
If you want to match regardless of uppercase/lowercase (like catching "HI" or "HELLO"), convert both the input and keywords to lowercase for comparison:
greetings = ['hi', 'hello', 'hey', 'hi there'] # Convert user input to lowercase first user_input = input("Enter your text: ").lower() for keyword in greetings: if keyword in user_input: print("Matched a greeting keyword!") break else: print("No preset keywords matched your input.")
Extra Tips for Expansion
- If you want to match whole words only (so "hiking" doesn't trigger a "hi" match), split the input into individual words first:
user_words = user_input.lower().split() if any(kw in user_words for kw in greetings): print("Matched a whole-word greeting!") - Wrap the matching logic into a function for reusability:
def has_keyword(input_text, keyword_list): lower_text = input_text.lower() return any(kw.lower() in lower_text for kw in keyword_list) # Use the function greetings = ['hi', 'hello', 'hey'] user_input = input("Enter your text: ") if has_keyword(user_input, greetings): print("Match found!") else: print("No keywords matched.")
Take it step by step—start with the basic version, tweak it to fit your needs, and experiment with small changes as you learn. Self-teaching is all about trial and error, and you're already making great progress!
内容的提问来源于stack exchange,提问作者Artificial Intelligence

