读取文件并将其格式化为字典

2024-09-28 01:27:18 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在function.py中捕获字符串,并将def step1()及其后续函数create()login()跟踪为字典格式?(我想要实现的格式如下所示)

function.py

#!C:\Python\Python39\python.exe
# print ('Content-type: text/html\n\n')

def step1():
    create()
    login()

def step2():
    authenticate()

def step3():
    send()

预期产出

thisdict = {
  'def step1()': ['create(),login()'],
  'def step2():':['authenticate()'],
  'def step3():': ['send()']
}

Tags: 函数字符串pysend字典def格式create
3条回答

您可以读取文件function.py,将其拆分以分离不同的函数,然后对每个函数再次拆分,以获得签名作为键,命令作为值:

with open('function.py', 'r') as inFile:
    funcs = inFile.read().split('\n\n')[1:]
    result = {}
    for elem in funcs:
        sign, commands = elem.split(':')
        commands = list(map(str.strip, commands.split('\n')))[1:]
        result.update({sign : commands})
    print(result)

这将返回:

{'def step1()': ['create()', 'login()'], 'def step2()': ['authenticate()'], 'def step3()': ['send()']}

你可以这样做:

with open('function.py', 'r') as f:
    file = f.readlines()

thisdict = {'start':[]}
temp = []
a = '_start_' #just to get the first lines if there is some things before the first function
for line in file:
    if line.startsWith('def'): #You might want to add something for the spacing
        thisdict[a] = temp
        a = line[3:]
        temp=[]
    else:
        temp.append(line)
thisdict[a] = temp

print(thisdict)

这显然不是最好的代码,但很容易理解和实现:)

您可以使用一个正则表达式来查找每个方法和内容(def \w+\(.*\):)((?:\n[ \t]+.+)+)

  • (def \w+\(.*\):)用于方法定义

  • \n[ \t]+.+用于每个方法行(与前面的\n

import json
import re

with open("function.py") as fic:
    content = fic.read()

groups = re.findall(r"(def \w+\(.*\):)((?:\n[ \t]+.+)+)", content)
result = {key: [",".join(map(str.strip, val.strip().splitlines()))]
          for key, val in groups}
print(json.dumps(result, indent=4))

相关问题 更多 >

    热门问题