我只是想檢查是否有任何更好的方法來做到這一點,而不是使用我想出來的。使用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
所以包裝這件事,有什麼我可以提高?
爲什麼不只是導入文件並訪問'我d_list'直接? – jonrsharpe
'id_list = list()'怎麼辦?或者'x = []'然後'id_list = x'? – cdarke
@jonrsharpe不太確定是否應該這樣做,因爲有很多文件需要解析,一次導入所有文件不會是我想的好主意。 –