Python 的 get_close_matches() 怎样给输错的子命令提供提示?
用 Python 的 get_close_matches() 为未知子命令给出拼写提示,并用 n 和 cutoff 控制候选数量与相似度。
当命令行程序接收到 stats 指令时,可先校验可用命令集。若未找到精确匹配项,则利用 difflib.get_close_matches() 搜索拼写相近的命令,比如提示用户输入 status。
先判断命令名是否完全匹配
示例代码将合法命令名称存储于 commands 内。一旦实现精确匹配,系统即输出 accepted 并继续处理后续输入。因此 stop 命令能直接通过验证,仅当遇到未知命令时才触发拼写匹配逻辑。
为未知命令查找候选
get_close_matches() 用于对比用户输入与候选命令列表。通过配置 n=1 限制最多只返回一个最相似的结果,同时 cutoff=0.75 会剔除相似度不足 0.75 的选项。若未能找到匹配项,函数将返回空列表,程序需先判空再获取首个元素。
from difflib import get_close_matches
commands = ["status", "start", "stop"]
for command in ("stop", "stats", "xyz"):
if command in commands:
print(f"{command}: accepted")
continue
matches = get_close_matches(command, commands, n=1, cutoff=0.75)
if matches:
print(f"{command}: did you mean {matches[0]}?")
else:
print(f"{command}: no suggestion")
查看三种输入的结果
由于 stop 存在于命令列表中,系统将显示 accepted。stats 与 status 仅相差一个字母 u,二者最为接近,故系统给出拼写建议。而 xyz 与任何候选命令均无共同字符,因此系统提示 no suggestion。
预期输出
stop: accepted
stats: did you mean status?
xyz: no suggestion
把拼写提示和执行分开
在实际应用中,程序可向用户展示候选命令,待用户确认或输入完整的有效指令后再执行。我们可以利用项目中常见的拼写错误来验证提示效果,并据此调整 cutoff。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













