这种方法比其他方法更冗长,但根据几个因素(见最后的笔记),它可能更有效。除非您正在处理大量配置项目的大量文件,否则我甚至不会考虑将其用于某些其他建议,但如果性能成为问题,则此算法可能会有所帮助。
开始从配置字符串的文件集(称之为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