2017-12-07 2 views
0

저는 파이썬을 처음 사용하고 있으며 파일을 파싱하려고합니다. 나는이 형식을 가진 파일이 있습니다 파이썬 - 파일을 파싱하고 객체를 저장하십시오.

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

하지만이 오브젝트/아이템을 저장하는 가장 좋은 방법은 무엇입니까? 모든 수트 또는 샘플 코드를 환영합니다. 고마워요

+0

을 이해하는 것이 아마도 가장 쉬운 방법입니다 함수 이름으로서의 키와 args의리스트로서의 값. – cdarke

답변

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'}} 

가이 일을하는 다른 방법이 있지만 이것은 당신과 함께 항목을 저장하는 사전을 사용 나는 제안

+0

는 file.read(). split ('Function')을 사용할 수 있습니다. strip() 모든 공백 – newbie

+0

@newbie'split()'은 –

+0

에 'strip()'을 사용할 수없는 목록을 반환합니다. ,이 줄'd [func [0]] = set (func [2 : -1])의 의미를 설명해 주시겠습니까? – Eis

관련 문제