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

输入驱动的多条件嵌套判断代码问题与交互逻辑优化需求

问题描述

我正在开发一个简单的文本交互系统,希望用户输入对应指令时能触发正确输出,但当前代码运行异常,需要修正依赖输入的外层条件判断逻辑问题,同时保留各独立指令路径。

当前代码

import time
P = 95
west = 'west'
north = 'north'
south = 'south'
east = 'east'
lamp = 'lamp' 'light fixture' 'lamp'
grab = 'grab', 'get,', 'retrive','take'
go = 'go', 'tavel', 'walk', 'run'
put_down = 'place', 'drop', 'put'
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++#
#*similarity functions*#
from difflib import SequenceMatcher
def similar(a, b):
 return SequenceMatcher(None, a, b).ratio()
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++#
#print("wait for it")
#time.sleep(10)
#print("i just wasted 10 seconds of your life")
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++#
def lampIn(stat):
 return 'lamp' in stat or 'light fixture' in stat
def grabIn(stat):
 return 'grab' in stat or 'get,' in stat or 'retrive' in stat or 'take' in stat
def westIn(stat):
 return 'west' in stat
def northIn(stat):
 return 'north' in stat
def southIn(stat):
 return 'south' in stat
def eastIn(stat):
 return 'east' in stat
def grabIn(stat):
 return 'grab' in stat or 'get' in stat or 'retrieve' in stat or 'take' in stat
def goIn(stat):
 return 'go' in stat or 'travel' in stat or 'walk' in stat or 'run'
def put_downIn(stat):
 return 'place' in stat or 'drop' in stat or 'put' in stat
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++#
while True:
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++#
 statement = input()
 statement = statement.lower()
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++#
 resultGrab = similar(grab, statement)
 grabResult = grabIn(statement)
 for grabResult in statement or resultGrab >= P:
 print("what are you getting?")
#+++++++++++++++++++++++++++++++++++++++++++++++++++++#
 statement = input()
 statement = statement.lower()
#+++++++++++++++++++++++++++++++++++++++++++++++++++++#
 resultLamp = similar(lamp, statement)
 lampResult = lampIn(statement)
 for lampResult in statement or resultLamp >= P:
 print("you now have the lamp")
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++#
 resultGo = similar(go, statement)
 goResult = goIn(statement)
 for goResult in statement or resultGo >= P:
 print("Where?")
#+++++++++++++++++++++++++++++++++++++++++++++++++++++#
 statement = input()
 statement = statement.lower()
#+++++++++++++++++++++++++++++++++++++++++++++++++++++#
 resultWest = similar(west, statement)
 westResult = westIn(statement)
 for westResult in statement or resultWest >= P:
 print("You went west.")
 else:
 print("not a command yet")

运行异常情况

>>>walk
what are you getting?
est
you now have the lamp
you now have the lamp
you now have the lamp
you now have the lamp
what are you getting?

期望交互效果

>>>walk
where?
west
You went west

解决方案

嘿,你的代码主要踩了几个逻辑坑:重复读取输入、用循环代替条件判断、相似度函数使用错误,还有指令匹配逻辑混乱。我帮你修正了这些问题,同时保留了所有独立指令路径,下面是完整修复代码和问题说明:

修正后的完整代码

import time
from difflib import SequenceMatcher

# 整理指令集合和配置常量,让代码更整洁
SIMILARITY_THRESHOLD = 0.7  # 原95的阈值太苛刻,调松到0.7更符合交互预期
DIRECTIONS = {'west', 'north', 'south', 'east'}
GRAB_COMMANDS = {'grab', 'get', 'retrieve', 'take'}
GO_COMMANDS = {'go', 'travel', 'walk', 'run'}
PUT_DOWN_COMMANDS = {'place', 'drop', 'put'}
LAMP_TERMS = {'lamp', 'light fixture'}

def similar(a, b):
    return SequenceMatcher(None, a.lower(), b.lower()).ratio()

# 通用指令匹配函数,避免重复编写多个In函数
def is_command_match(statement, command_set, threshold=SIMILARITY_THRESHOLD):
    for cmd in command_set:
        # 支持完全匹配或相似度达标两种情况
        if cmd in statement or similar(cmd, statement) >= threshold:
            return True
    return False

def main():
    inventory = set()  # 用集合管理玩家物品,方便判断持有状态
    while True:
        statement = input(">>>").lower().strip()
        
        # 处理移动指令:先匹配"移动类"指令,再询问方向
        if is_command_match(statement, GO_COMMANDS):
            print("Where?")
            direction = input(">>>").lower().strip()
            if is_command_match(direction, DIRECTIONS):
                print(f"You went {direction}.")
            else:
                print("Invalid direction. Try west/north/south/east.")
        
        # 处理抓取物品指令:先匹配"抓取类"指令,再询问物品
        elif is_command_match(statement, GRAB_COMMANDS):
            print("What are you getting?")
            item = input(">>>").lower().strip()
            if is_command_match(item, LAMP_TERMS):
                inventory.add('lamp')
                print("You now have the lamp.")
            else:
                print(f"Sorry, I don't recognize the item '{item}'.")
        
        # 处理放下物品指令
        elif is_command_match(statement, PUT_DOWN_COMMANDS):
            if not inventory:
                print("You don't have anything to put down!")
                continue
            print("What are you putting down?")
            item = input(">>>").lower().strip()
            if is_command_match(item, LAMP_TERMS) and 'lamp' in inventory:
                inventory.remove('lamp')
                print("You put down the lamp.")
            else:
                print(f"You don't have '{item}' in your inventory.")
        
        # 退出指令(方便测试的附加功能)
        elif statement in {'quit', 'exit'}:
            print("See you later!")
            break
        
        # 未知指令提示
        else:
            print("Hmm, that's not a valid command. Try things like 'walk', 'grab', or 'drop'.")

if __name__ == "__main__":
    main()

主要修复的问题点

  • 重复读取输入:原代码在循环中反复调用input(),导致输入与逻辑完全错位,现在仅在循环开头读取一次输入,根据指令类型再决定是否读取后续的方向/物品输入。
  • 错误的循环判断:你之前用for grabResult in statement or resultGrab >= P:这种完全错误的写法,这里应该用if条件判断而非for循环——你不需要遍历,只需要判断是否匹配即可。
  • 相似度函数使用错误:原代码直接将整个指令元组传给similar函数,无法正确计算相似度,现在改为遍历每个指令词,分别与用户输入计算相似度。
  • 重复定义函数:你之前重复编写了两次grabIn函数,后面的函数直接覆盖了前面的,现在用一个通用的is_command_match函数处理所有指令匹配,避免重复代码。
  • 阈值设置不合理:原P=95的阈值要求输入与指令几乎完全一致才能匹配,调松到0.7后,用户输入类似wak也能匹配到walk,更符合交互预期。
  • 缺少状态管理:新增inventory集合跟踪玩家持有的物品,让放下物品这类逻辑更合理。

测试效果

运行修正后的代码,就能得到你期望的交互:

>>>walk
Where?
>>>west
You went west.

抓取灯的交互也正常:

>>>grab
What are you getting?
>>>lamp
You now have the lamp.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:24:46