0

I'm new to python and I m trying to parse a file. I have a file with this format :

Function func1
(
  arg1 arg1
  arg2 arg2
);

Function func2
(
  arg3 arg3
);

its pretty repetitive. I'm tryin to parse this file and search for certain functions only and store their args into a list/object (I don't know exactly how) and reuse these infos to write to a file. I started my code like this

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))

But I don't what is the best way to proceed to store this objects/items. Any suggets or sample codes are welcome. thank you

newbie
  • 137
  • 2
  • 11
Eis
  • 11
  • 2
  • I suggest you use a dictionary to store the items, with the key as the function name and the value as a list of args. – cdarke Dec 07 '17 at 11:01

1 Answers1

0

You could split by "Function" to get a list consisting of each function. Then use a dictionary to store the name of the function and its arguments. Something like this:

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

Output:

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

There are other ways of doing this but this is probably the easiest to understand

Farhan.K
  • 3,425
  • 2
  • 15
  • 26
  • @newbie `split()` returns a list which you can't use `strip()` on – Farhan.K Dec 07 '17 at 11:26
  • Thank you for your answer, can you explain please the meaning of this line `d[func[0]] = set(func[2:-1])`? – Eis Dec 08 '17 at 10:23
  • @Eis That line assigns the name of the function (`func[0]`) as the key in `d` and the value as `set(func[2:-1])`. `func[2:-1]` is [list slicing](https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation) and `set` is used to remove duplicates (eg. `arg1 arg1`) – Farhan.K Dec 11 '17 at 10:57