![](/img/trans.png)
[英]How to use commands from a txt file and store Python outputs in a txt file
[英]How to load commands from txt file, python
我有一个如下的文本文件:
Run
Jump
Jump
Swim
Run
我有 3 种方法,跑步、跳跃和游泳,当每一行被读取时,我如何运行这些函数,所以它会先运行“运行”,然后运行 function,然后运行“跳转”function两次等,我被困了 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 语句及其他语句打开文本文件,读取命令,删除任何空格,然后通过从字典中提取 function 来执行它。
我认为您应该只拥有一本包含命令+功能的字典:
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.