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

如何提升用户输入语句通用性?卡牌输入兼容优化问询

实现卡牌选择输入的通用性兼容

要让用户输入不用严格匹配栈中存储的格式,可从大小写兼容、缩写映射、输入预处理三个方面修改代码,具体方案如下:

1. 定义类型映射规则

先做一个覆盖全拼、缩写的映射字典,把各种合法输入对应到栈中存储的标准卡牌类型,比如:

card_type_mapping = {
    "spade": "Spade",
    "s": "Spade",
    "heart": "Heart",
    "h": "Heart",
    "diamond": "Diamond",
    "d": "Diamond",
    "club": "Club",
    "c": "Club"
}

2. 统一输入预处理

对用户输入的卡牌类型做标准化处理:

  • 去除首尾空格(避免误输入空格导致匹配失败)
  • 转成小写(消除大小写差异)
  • 通过映射字典转换成栈中存储的标准类型

3. 卡牌数字的兼容处理

如果栈中存储的数字是整数类型,要把用户输入的字符串转成整数;如果是字符串,就统一转成相同格式(比如去空格)再比较。

修改后的完整代码

def selectCard():
    # 定义类型映射,覆盖全拼、缩写,兼容大小写
    card_type_mapping = {
        "spade": "Spade",
        "s": "Spade",
        "heart": "Heart",
        "h": "Heart",
        "diamond": "Diamond",
        "d": "Diamond",
        "club": "Club",
        "c": "Club"
    }
    
    # 获取并预处理用户输入
    user_type_input = input("Enter the type of the Card you want to select:").strip().lower()
    user_number_input = input("Enter the number of the Card you want to select:").strip()
    
    # 转换为标准类型,输入不合法则提示并返回
    try:
        standard_card_type = card_type_mapping[user_type_input]
    except KeyError:
        print("无效卡牌类型!请输入 Spade/S, Heart/H, Diamond/D, Club/C")
        return
    
    # 遍历栈匹配卡牌(假设栈中数字为字符串,若为整数则改为 int(user_number_input))
    for card in stack:
        if card.type == standard_card_type and str(card.number) == user_number_input:
            useCard(standard_card_type, user_number_input)
            return
    print("栈中未找到该卡牌!")

额外优化点

  • 可把映射字典和输入提示提取成全局常量,方便后续维护
  • 若要支持更模糊的输入,可增加部分匹配逻辑(比如输入"spa"也能匹配Spade),但需注意处理歧义情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 03:31:36