Python - 解析文件&存储对象

时间:2017-12-07 10:49:22

标签: python

我是python的新手,我试图解析一个文件。 我有一个这种格式的文件:

Function func1
(
  arg1 arg1
  arg2 arg2
);

Function func2
(
  arg3 arg3
);

非常重复。我正在尝试解析此文件并仅搜索某些函数并将其args存储到列表/对象中(我不确切知道如何)并重用这些信息来写入文件。我像这样开始了我的代码

def get_wanted_funcs(path,list_func):
    f = open(path,'r')
    while True:
        text = f.readline()
        if list_func in text:
           ## store name of func + args 
templ = myfile_h()
# something like templ.stored_objects = stored_objects 
with open(os.path.join(generated_dir, "myfile.h"), "w") as f:
            f.write(str(templ))

但我不知道存储此对象/项目的最佳方法是什么。欢迎任何建议或样本代码。谢谢

1 个答案:

答案 0 :(得分:0)

您可以按"Function"拆分以获取包含每个功能的列表。然后使用字典存储函数的名称及其参数。像这样:

with open(path, 'r') as file:
    functions = file.read().split('Function')
    functions = functions[1:] # This is to get rid of the blank item at the start due to 'Function' being at the start of the file.

# Right now `functions` looks like this:
# [' func1\n(\n  arg1 arg1\n  arg2 arg2\n);\n\n', ' func2\n(\n  arg3 arg3\n);\n', ' func3\n(\n  arg4 arg4\n  arg5 arg5\n);\n\n', ' func4\n(\n  arg6 arg6\n);']

functions_to_save = ['func1'] # This is a list of functions that we want to save. You can change this to a list of whichever functions you need to save


d = {} # Dictionary

# Next we can split each item in `functions` by whitespace and use slicing to get the arguments

for func in functions:
    func = func.split() # ['func1', '(', 'arg1', 'arg1', 'arg2', 'arg2', ');']
    if func[0] in functions_to_save:
        d[func[0]] = set(func[2:-1]) # set is used to get rid of duplicates

输出:

>>> d
{'func1': {'arg2', 'arg1'}}

还有其他方法可以做到这一点,但这可能是最容易理解的