2016-11-28 39 views
0

我只是想檢查是否有任何更好的方法來做到這一點,而不是使用我想出來的。使用python解析.py文件中的特定命名列表

的事情是,我需要解析.py文件,更確切地說我必須尋找一個包含若干int數字的具體list名爲ID_LIST。數字可以用多種格式書寫。

例如:

id_list = [123456, 789123, 456789]

id_list = [ 123456, 
       789123, 
       456789 ] 

id_list = [ 123456 
       ,789123 
       ,456789 ] 

什麼,我想出了作品就好了,但是對於完美主義的緣故,我想知道是否有「平滑」這樣做的方式。

with open(filepath, 'rb') as input_file: 
    parsed_string = '' 
    start_flag = False 
    start_parsing = False 
    for line in input_file: 
     if 'id_list' in line: 
      id_detected = True 
     if id_detected: 
      for char in line: 
       if char == '[': 
        start_parsing = True 
       if start_parsing and char != '\n': 
        parsed_string += char 
       if char == ']': 
        id_detected = False 
        start_parsing = False 
        break 

之後已經做IM只是過濾parsed_string

new_string = "".join(filter(lambda char: char.isdigit() or char == ',', parsed_string)) 

這讓我包含數字和逗號字符串:123456,789123,456789

所以包裝這件事,有什麼我可以提高?

+4

爲什麼不只是導入文件並訪問'我d_list'直接? – jonrsharpe

+0

'id_list = list()'怎麼辦?或者'x = []'然後'id_list = x'? – cdarke

+0

@jonrsharpe不太確定是否應該這樣做,因爲有很多文件需要解析,一次導入所有文件不會是我想的好主意。 –

回答

2

您可以使用正則表達式來解決:

import re 

with open(filepath, 'rb') as input_file: 
    text = input_file.read() 
    match = re.search(r'id_list\s*=\s*\[(.*?)\]', text, flags=re.DOTALL) 

    if match is None: 
     print "Not found" 

    else: 
     id_list_str = match.group(1) 
     id_list = map(int, id_list_str.split(',')) 
     print id_list 
+0

通常應避免使用'eval'和'exec',因爲它們可能存在安全風險。詳情請參閱[評估真的很危險](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous。HTML)由SO老將Ned Batchelder。相反,你可以使用更安全的選擇:'ast.literal_eval'。 –

+0

手動解析數據絕對安全得多! –

0

只是使用importfrom

如果你不想導入整個Python文件只需要導入需要

元素

示例

from filename.py import id_list