Python根据用户输入触发不同响应的进阶需求咨询
Hey there! Great start with your basic input-matching program—let's build on that to handle more complex cases like math formulas and specific custom triggers. Here's a step-by-step breakdown with actionable code examples:
1. Refactor for Maintainability
First, let's clean up your existing code into reusable components so adding new triggers doesn't mean rewriting the same if/else logic over and over. A simple function or rule dictionary will make scaling way easier:
def process_input(user_input): # Normalize input to handle case insensitivity lower_input = user_input.lower() # Basic keyword matches (your original logic) if "yes" in lower_input: return "resp1 is yes" elif "no" in lower_input: return "resp2 is no" # We'll add new triggers here else: return "I don't recognize that input." # Add a loop so you can test multiple inputs without restarting while True: resp = input("Enter your input (type 'quit' to exit): ") if resp.lower() == "quit": break print(process_input(resp))
2. Detect Math Formulas
To spot math expressions, use regular expressions to match common math syntax (numbers, operators, parentheses). Here's how to integrate that into your function:
import re def is_math_expression(input_str): # Regex pattern to match meaningful math sequences (avoids single digits) math_pattern = re.compile(r'(\d+[\+\-\*\/\^\(\)]|\([\d\+\-\*\/]+\))+') match = math_pattern.search(input_str) # Ensure we're catching actual formulas, not just random characters return match is not None and len(match.group()) >= 3 def process_input(user_input): lower_input = user_input.lower() # Check for math formulas first (higher priority) if is_math_expression(user_input): # Optional: Calculate the result (note: eval has security risks for untrusted input!) try: result = eval(user_input) return f"You entered a math formula! Result: {result}" except: return "That looks like a math formula, but I can't calculate it—check your syntax!" elif "yes" in lower_input: return "resp1 is yes" elif "no" in lower_input: return "resp2 is no" else: return "I don't recognize that input."
⚠️ Security Note: Using eval() on user input is risky if this program will handle untrusted users. For production use, stick to safe parsers like ast.literal_eval() (limited to literals) or dedicated math parsing libraries.
3. Add More Complex Triggers
You can expand this pattern to handle other specific inputs—like dates, custom phrases, or technical terms. For cleaner code, use a dictionary to map triggers to responses:
# Example: Dictionary-based trigger mapping for easy updates trigger_map = { "yes": "resp1 is yes", "no": "resp2 is no", "hello": "Hi there! 😊", "how are you": "I'm just a program, but thanks for asking!", "help": "I can respond to 'yes', 'no', math formulas, or basic greetings!" } def process_input(user_input): lower_input = user_input.lower() # Check math first if is_math_expression(user_input): # ... math logic as before ... # Check trigger map for partial matches for trigger, response in trigger_map.items(): if trigger in lower_input: return response return "I don't recognize that input."
4. Scale Further with Intent Recognition
If you want to handle natural language inputs (not just keyword matches), look into lightweight intent recognition libraries like spaCy or Rasa NLU—these let you train models to understand what the user is asking, not just what words they used.
内容的提问来源于stack exchange,提问作者crater

