我正在制作一个从数据库中获取discgolf数据的ircbot。我想在字典中存储可能的命令:
function_dictionary = {"get PLAYERS best round from COURSE on YEAR" :
get_best_round,
"get PLAYERS THINGS from COURSE on YEAR" : get_things}
玩家,课程等将存储在列表中。
PLAYERS = ["name1", "name2", "name3"]
COURSES = ["course1", "course2", "course3"]
THINGS = ["birdies", "pars", "bogeys"]
YEARS = [2015, 2016, 2017]
如果所有参数都是由用户提供的,我可以替换参数并保存原始值:
userinput = "get name1 best round from course1 on 2016"
for p in PLAYERS:
if p in userinput:
player = p
userinput = userinput.replace(p, "PLAYERS")
for c in COURSES:
if c in userinput:
course = c
userinput = userinput.replace(c, "COURSE")
for y in YEARS:
if y in userinput:
year = y
userinput = userinput.replace(y, "YEAR")
然后搜索命令是否在字典中:
for key in function_dictionary:
if key in userinput:
func_to_run = function_dictionary[key]
func_to_run(player, course, year)
如果用户输入中缺少一个或多个参数,我将如何工作?
userinput1 = "get name1 best round"
应触发:
get_best_round("name1", course = "all", year = "all")
和
userinput2 = "get best round from course1"
应触发:
get_best_round(name = "all", "course1", year = "all")
和
userinput3 = "get birdies on 2016"
shoud trigger
get_things(name = "all", "birdies", course = "all", 2016)
答案 0 :(得分:1)
只需添加条款即可表明如果在userinput中未选择播放器/课程/年份,则默认为您选择的值:
pset = False
for p in PLAYERS:
if p in userinput:
pset=True
player = p
userinput = userinput.replace(p, "PLAYERS")
if pset==False:
player= #value for any player
并重复课程和年份。
答案 1 :(得分:1)
你可以使用一些旗帜。
例如:
for (var i=0; i < names.length; i++) {
console.log ("I know someone called"+" "+names[i]+".");
}
然后,您只需检查布尔值并调用适当的方法。
但是,我不会采用这种方法。它似乎有足够的失败点。也许搜索PLAYERS_inserted = False
for p in PLAYERS:
if p in userinput:
player = p
userinput = userinput.replace(p, "PLAYERS")
PLAYERS_inserted = True
COURSES_inserted = False
for c in COURSES:
if c in userinput:
course = c
userinput = userinput.replace(c, "COURSE")
COURSES_inserted = True
YEARS_inserted = False
for y in YEARS:
if y in userinput:
year = y
userinput = userinput.replace(y, "YEAR")
YEAR_inserted = True
和/或构建一个更具体的界面。