gpt4 book ai didi

python - 将文件值转换为 dict (Python)

转载 作者:太空宇宙 更新时间:2023-11-03 21:28:55 24 4
gpt4 key购买 nike

非常感谢您的帮助,因为我正在努力完成最终产品,并且我需要在不使用导入功能的情况下完成此操作。

我需要编写一个函数来打开并读取文件,返回一个字典,其中每个键是函数的名称,值是函数参数的列表。并且应该返回类似这样的东西。

{"h":[x], "f":[a, b], "g":[c]}

我正在传输的文件如下所示

def h(x):
f(x + 4, 9)

def f(a, b):
e = a * b
g(e)

def g(c):
b = 3

打印(c)

打印(b)

到目前为止,我的代码看起来像这样,但我不知道如何使它看起来像字典中的最终产品。

filename=""

ddd=dict()

new=list()


def take_name():

global filename

filename= input("Please, type the name of the file:")

print(take_name())



def open_read():

global handle

handle= open(filename, 'r')

for line in handle:

line=line.rstrip()

if line.startswith('def'):

line=line.replace('def', " ")

line=line.replace(':', " ")


new.append(line)



print(new)

print(ddd)


print(open_read())

再次感谢您的帮助

最佳答案

不确定为什么您需要另一个列表,但这应该适用于出现一次的函数。对于重复函数,它将用最新遇到的参数替换该值

def open_read():

global handle

handle= open(filename, 'r')

for line in handle:

line=line.rstrip()

if line.startswith('def'):

line=line.replace('def', " ")
ddd[line[0:line.index('(')].strip()]=line[line.index('(')+1:line.index(')')].split(',')

关于python - 将文件值转换为 dict (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53657068/

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