遍历去匹配
import sys
# 存放命令
cmd = {
'reset': 'reset what',
'reset board': 'board fault',
'board add': 'where to add',
'board delete': 'no board at all',
'reboot backplane': 'impossible',
'backplane abort': 'install first'
}
# 循环输入
unknow = 'unknown command'
for s in sys.stdin:
s = s.strip().split() # 格式化输入,以空格为界限存入tuple
match_cmd = list() # 命中命令保存结果
if len(s) == 0:
break
# 遍历配置文件命令,去匹配输入命令
for c in cmd:
index_word = 0 # 匹配命令的单词下标
cmd_word = c.split() # 格式化配置文件中的命令
# 如果输入的命令单词数大于配置文件命令单词数,则跳过该条配置文件命令,继续匹配
if len(s) != len(cmd_word):
continue
# 遍历输入的命令
for seg_s in s:
# 从第一个字符开始匹配,如果输入的单词是命令单词的子串,则认为匹配成功,匹配单词下标+1。否则跳过该命令。
if cmd_word[index_word].find(seg_s) == 0:
index_word += 1
else:
break
# 判断命令的所有单词是否都匹配成功
if index_word == len(cmd_word):
match_cmd.append(c)
# 判断全匹配个数
if len(match_cmd) == 1:
print(c***tch_cmd[0]])
else:
print(unknow) 
京公网安备 11010502036488号