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

Python代码优化:实现匹配特定短语后仅输出子系统查询结果而非重复执行命令

Fixing the Duplicate Output Issue for "find subsystem" Commands

Let's work through this problem together. The core issue here is that your current code uses three separate if statements instead of a structured conditional chain—so when you enter a "find subsystem" command, it triggers both the dedicated find block and the final else block (since the input isn't "quit" or "clear").

Here's a polished solution that fixes the duplicate output and also extracts just the subsystem name like you wanted:

Modified Code

x = 1 
while x <= 2: 
    text = input("> ") 
    to_deny = "!?/" 
    find_trigger = "find subsystem"  # Simplify to a single string for cleaner checking
    
    # First validate input for restricted characters
    if any(char in text for char in to_deny): 
        print("text contains restricted characters") 
        quit() 
    
    # Use a mutually exclusive conditional chain to avoid duplicate actions
    if text == "quit": 
        quit() 
    elif text == "clear": 
        import os 
        os.system("clear") 
    elif find_trigger in text: 
        # Extract the subsystem name by stripping the trigger text and extra whitespace
        subsystem_name = text.replace(find_trigger, "").strip()
        # Handle edge case where user only entered the trigger without a name
        if not subsystem_name:
            print("Please add a subsystem name after 'find subsystem'")
        else:
            print(f"finding subsystem: {subsystem_name}")
    else: 
        print(f"running {text}....") 

Key Improvements Explained:

  • Mutually Exclusive Logic: Switched to if/elif/else so only one code block runs per input. This stops the "running..." message from appearing when we process a "find subsystem" command.
  • Cleaner Subsystem Extraction: We remove the "find subsystem" text from the input and strip extra spaces to get a clean subsystem name. We also added a check to handle cases where the user forgets to add a subsystem name.
  • Simplified Trigger Check: Replaced the single-item find list with a string variable for more straightforward readability.

Now when you enter something like "find subsystem payment", you'll only see finding subsystem: payment without the extra "running..." line.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 01:03:10