简体   繁体   English

如何从 txt 文件加载命令,python

[英]How to load commands from txt file, python

I have a text file that follows:我有一个如下的文本文件:

Run
Jump
Jump
Swim
Run

And I have 3 methods, run, jump and swim, how do I run those functions when each of those lines gets read, so it would run "Run" first and that would run the run function then it would run the "Jump" function twice ect, ive been stuck for 2 days and thought a hint would be much appreciated, thanks!我有 3 种方法,跑步、跳跃和游泳,当每一行被读取时,我如何运行这些函数,所以它会先运行“运行”,然后运行 function,然后运行“跳转”function两次等,我被困了 2 天,并认为提示将不胜感激,谢谢! ^-^ ^-^

This is what I would do:这就是我要做的:

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]()

We use a dictionary to store the relationship between the commands in the text file and the functions that need to be executed.我们使用字典来存储文本文件中的命令与需要执行的函数之间的关系。

The with statement and beyond opens the text file, reads the commands in, removes any whitespace and then executes the function by extracting it from the dictionary. with 语句及其他语句打开文本文件,读取命令,删除任何空格,然后通过从字典中提取 function 来执行它。

I think you should just have a dictionary that holds commands+functions:我认为您应该只拥有一本包含命令+功能的字典:

def jump():
   player.y += 10 
    ...

commands = {"jump":jump,"Run":run,"Swim":swim}
for cmd in command_file.split("\n"):
    commands.get(cmd.strip())()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM