這種方法比其他方法更冗長,但根據幾個因素(見最後的筆記),它可能更有效。除非您正在處理大量配置項目的大量文件,否則我甚至不會考慮將其用於某些其他建議,但如果性能成爲問題,則此算法可能會有所幫助。
開始從配置字符串的文件集(稱之爲c2f
,並從文件設置配置字符串(f2c
)。兩者都可以作爲你glob的文件建立一個字典。
要clear,c2f是一個字典,其中鍵是字符串,值是文件集f2c是字典,其中鍵是文件,值是字符串集
循環遍歷文件鍵f2c和一個數據項目,使用c2f查找所有包含該項目的文件,這些是你需要比較的唯一文件。
這裏的工作代碼:
# this structure simulates the files system and contents.
cfg_data = {
"config1.txt": ["1.1.1.1", "2.2.2.2"],
"config2.txt": ["1.1.1.1"],
"config3.txt": ["2.2.2.2", "1.1.1.1"],
"config4.txt": ["2.2.2.2"]
}
# Build the dictionaries (this is O(n) over the lines of configuration data)
f2c = dict()
c2f = dict()
for file, data in cfg_data.iteritems():
data_set = set()
for item in data:
data_set.add(item)
if not item in c2f:
c2f[item] = set()
c2f[item].add(file)
f2c[file] = data_set;
# build the results as a list of pairs of lists:
results = []
# track the processed files
processed = set()
for file, data in f2c.iteritems():
if file in processed:
continue
size = len(data)
equivalence_list = []
# get one item from data, preferably the one used by the smallest list of
# files.
item = None
item_files = 0
for i in data:
if item == None:
item = i
item_files = len(c2f[item])
elif len(c2f[i]) < item_files:
item = i
item_files = len(c2f[i])
# All files with the same data as f must have at least the first item of
# data, just look at those files.
for other_file in c2f[item]:
other_data = f2c[other_file]
if other_data == data:
equivalence_list.append(other_file)
# No need to visit these files again
processed.add(other_file)
results.append((data, equivalence_list))
# Display the results
for data, files in results:
print data, ':', files
添加上計算複雜注:這在技術上是O((K數N)*(L日誌M)),其中N爲文件的數量,M是(< = N)是具有相同內容和L的文件的組的數量 L(< = M)是必須成對比較的每個L的文件的平均數量處理文件。這應該是有效的,如果K < < N和L < < M.
「我明白如何glob文件目錄,循環glob結果並一次打開每個文件,並使用正則表達式匹配每一行」show我們的代碼,我們很樂意告訴你如何去做其餘的事情。提示:使用字典。 – agf