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/elseso 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
findlist 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
相关产品推荐
相关产品推荐

