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

时间:2021-07-04 10:27:10

标签: python

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

函数.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()']
}

3 个答案:

答案 0 :(得分:0)

您可以读取文件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()']}

答案 1 :(得分:0)

您可以使用正则表达式来查找每个方法和内容 (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))

答案 2 :(得分:0)

你可以这样做:

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)

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