问题描述
我有一个文本文件,内容如下:
Run
Jump
Jump
Swim
Run
我有 3 种方法,run、jump 和游泳,当每行被读取时我如何运行这些函数,所以它会先运行“Run”,然后运行 run 函数,然后它会运行“跳转”功能两次等,我被卡住了 2 天,并认为一个提示将不胜感激,谢谢! ^-^
解决方法
这就是我会做的:
def run():
print('Running')
def jump():
print('Jump')
def swim():
print('Swim')
commands_table = {'Run':run,'Jump':jump,'Swim':swim}
with open('commands.txt','r') as command_file:
for cmd in command_file:
cmd = cmd.strip()
commands_table[cmd]()
我们使用字典来存储文本文件中的命令与需要执行的函数之间的关系。
with 语句及其他语句打开文本文件,读取命令,删除任何空格,然后通过从字典中提取它来执行函数。
,我认为你应该有一个包含命令+函数的字典:
ResponseItemWidget