gpt4 book ai didi

python - 从 json 文件加载项目描述

转载 作者:行者123 更新时间:2023-12-05 04:29:44 25 4
gpt4 key购买 nike

最近我看到一篇帖子说有人制作了一个可以控制启动它的计算机的程序。 (就是这个)Add commands to user input我真的对它很感兴趣,我想复制它并在途中提高我的 Python 技能。

看完一些教程后,我能够发送和接收电子邮件并开始使用一些命令。首先,我添加了截屏功能,这是最重要的功能。然后我添加了函数和命令来做其他事情。然后我想添加一个帮助命令,如果没有 args 则显示所有命令,如果有 args 则显示特定命令的描述。我首先添加了没有参数的那个,这是它的代码:

import json

user_input = "$say hello\n$help"
def help(*args):
if args == ():
for func_name, aliases in info_json.items():
print(func_name)
else:
pass
#print the description for the command

def command1():
print("I am command 1.")
def command2():
print("I am command 2.")
def command3():
print("I am command 3.")
def say(*args):
print(f"You said i should say \"{' '.join(args)}\"! Very cool :D")
def pause(sec):
print(f"I waited for {sec} seconds!")

commands = {
"$help":help,
"$pause":pause,
"$say":say,
"$command1":command1,
"$command2":command2,
"$command3":command3,
}
with open("commands.json") as json_file:
help_json = json.load(json_file)


def call_command(BEFEHL):
function, *args = BEFEHL.split(' ')
commands[function](*args)


for line in user_input.split("\n"):
try:
call_command(line)
except KeyError:
print("This command does not exist.")

我像原作者那样用 print 语句替换了实际函数 :D

这段代码运行良好,我开始着手对具体功能进行描述。我创建了 commands.json 示例:

{
"command1": ["This command is command 1. It prints out 'I am command 1' "],
"command2": ["This command is command 2. It prints out 'I am command 2' "],
"command3": ["This command is command 3. It prints out 'I am command 3' "]
}

有什么方法可以打印出命令后面的 json 中的内容吗?一个示例用法是:

>>> $help command1
print("This is command 1. It prints out 'I am command 1' ")

我真的很想知道这是否可行! :D

最佳答案

当你加载一个 json 时,它基本上就像一个 Python 字典,所以你可以从它的 key 中检索命令的描述,你将它作为参数传递。

您的 help() 函数应如下所示:

def help(*args):
if args == ():
for func_name, aliases in help_json.items():
print(func_name)
else:
print(help_json.get(args[0], "Command does not exist"))

第二个参数 "Command does not exist" 是当 get() 无法在字典中找到键时打印的默认值。

关于python - 从 json 文件加载项目描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72239075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com