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

如何用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! 😊

实现Python 3关键词搜索功能的简单方案

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:10:43