我正在寫一個函數,它正在接受一些輸出,並根據其內容填充字典中的對象。 對象可以是2個組,並且取決於函數正在進行的文本文檔的哪一部分,在輸出中,我確定了類型1或類型2對象並使用相關數據填充它們。類型1對象通常位於State1文檔部分。 Type2對象 - 在State2 我主要依賴elif語句並處理輸入文本文件的每一行(作爲列表進入函數),以正則表達式查找其內容。然而,代碼變得難以管理 - 我正在將每一行都彙集到所有ifs中。 有沒有辦法讓這段代碼更好?Python - 改進基於正則表達式的輸出分析
def func(list):
#defining function related variables
state = ''
state1_specific_value1 = ''
state1_specific_value2 = ''
state1_specific_value3 = ''
state2_specific_value1 = ''
state2_specific_value2 = ''
state2_specific_value3 = ''
for i in list:
if REGEXP_DICTIONARY['state1_regexp'].match(i):
# processing state1 section
state = 'State1'
elif REGEXP_DICTIONARY['state2_regexp'].match(i):
# processing state2 section
state = 'State2'
elif REGEXP_DICTIONARY['interesting_line1_regexp'].match(i):
# detecting some special conditions for a jar. Is it twistable?
# not dependent on state
jar_dict[jar].Twistable = True
elif REGEXP_DICTIONARY['type'].match(i):
jar_type = clean(i.replace(" blablabla ", "")) # quick clean up jar related string to get jar's name.
#
# making decisions based on State delivered from previous lines and Type detected
#
if (state == "State1" and type == "Type1"):
debug("We detected State1 and Type 1")
elif (state == "State2" and type == "Type2"):
debug("We detected State2 and Type 2")
else:
debug ("inconsistency detected: type is {}, state is {}". format(type, state))
# State 1 Type1 related block
elif REGEXP_DICTIONARY['type1_state1_related regexp'].match(i) and state == "State1"
#do_something
elif ...
elif ...
elif ...
elif ...
#
# State 2 Type2 related block
elif REGEXP_DICTIONARY['type2_state2_related regexp'].match(i) and state == "State2":
#do_something
elif ...
elif ...
elif ...
elif ...