实现说明
逻辑集中在函数 suggest里。
迭代发生在 for typed in ["deplo", "statu", "rollbck", "logs-all", "zzz"] 内部——循环之外的语句只执行一遍。
使用要点
- 跑完文件,输出里会留下标记——
st @ 0.4:、st @ 0.6:。 - 把
suggest当作 API:导入它,其余代码可以忽略。
常见问题
除了语言运行时还需要什么准备?
什么都不需要——语言运行时是唯一要求。 全部导入都来自标准库:difflib。 文件在加载时定义 suggest。
主要签名是 def suggest(typed: str, cutoff: float = 0.6) -> list[str]
核心语句
def suggest(typed: str, cutoff: float = 0.6) -> list[str]:
# n caps the result count; cutoff is the required similarity floor.
return difflib.get_close_matches(typed, COMMANDS, n=2, cutoff=cutoff)
代码示例
import difflib
# A CLI offers these subcommands; typos map back to the nearest real one.
COMMANDS = ["deploy", "rollback", "status", "logs", "config", "destroy"]
def suggest(typed: str, cutoff: float = 0.6) -> list[str]:
# n caps the result count; cutoff is the required similarity floor.
return difflib.get_close_matches(typed, COMMANDS, n=2, cutoff=cutoff)
for typed in ["deplo", "statu", "rollbck", "logs-all", "zzz"]:
print(f"{typed!r} -> {suggest(typed) or 'no suggestion'}")
# cutoff sets how similar a candidate must be: 'st' clears 0.4 but not 0.6.
print("st @ 0.4:", difflib.get_close_matches("st", COMMANDS, n=1, cutoff=0.4))
print("st @ 0.6:", difflib.get_close_matches("st", COMMANDS, n=1, cutoff=0.6))