簡體   English   中英

(Python)將文件值轉換為dict

[英](Python) Converting file values to dict

我將在最終產品方面苦苦掙扎,對此將不勝感激。

我需要編寫一個打開並讀取文件的函數,返回一個字典,其中每個鍵是函數的名稱,而值是該函數的參數列表。 並且應該返回這樣的內容。

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

我正在傳輸的文件如下所示

定義h(x):

   f(x + 4, 9)

def f(a,b):

    e = a * b
    g(e)

定義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:")

打印(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)

打印(open_read())

再次感謝您的幫助

最好使用Python的解析器來完成工作,而不要使用正則表達式。

假設您的意思是{'h': ['x'], 'f': ['a', 'b'], 'g': ['c']} (因為{"h":[x], "f":[a, b], "g":[c]}看起來不是特別有用):

import ast

with open(filename) as f:
    code = f.read()
module = ast.parse(code, filename)
functions = { statement.name: [arg.arg for arg in statement.args.args]
    for statement in module.body if isinstance(statement, ast.FunctionDef)
}
print(functions)

但是,這只是一個基本片段,可能會更加復雜。 首先,它只會為您提供頂級功能(您需要一些遞歸才能捕獲子功能或方法)。 另一方面,它忽略除了位置(例如kwargs )之外的各種可能的參數。 如果您需要它們,則可以在了解AST的基礎后自行添加它們。

編輯: inspectast之間的顯着區別是您必須導入(即執行)源文件才能進行inspect ast對源文件本身起作用,而不執行它。 兩種方法都是有效的。 但是如果您對文件有安全性擔憂,或者您無法執行該文件(例如,由於依賴關系),或者如果您想從執行的代碼中獲取您無法獲取的內容(例如,我上面提到的本地定義的函數),應該更喜歡ast

您可以使用內置的python模塊檢查來完成所需的操作。 這里有一些代碼可以幫助您入門,在本示例中,我正在處理一個名為dummy.py的文件,但是您可以使用類似這樣的導入方式

import dummy
import inspect


members = inspect.getmembers(dummy)
for each in members:
    k,v = each
    if callable(v):
        args = inspect.getargspec(v)
        print(v, args)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM