需求:比对两源码文件的相似性。
思路1:利用Beyond Compare 4工具,文件夹比较,直接统计两源码文件相同文件(哈希值及文件名)数量,再分别计算占比。
思路2:先匹配出相对路径且文件名相同的文件,利用Beyond Compare 4工具,文本比较,分别得到文本比较结果,再依次统计出各文本内容的相似度(相同行/文本所有行)。
注:这里仅展示思路2的逻辑。
1. 匹配出相对路径且文件名相同的文件
def left_right_path_file(path):
'''文件夹(左右)下,所有文件的路径。
path 文件夹路径; keynum 相对路径截取位置
'''
file_path = []
keynum = len(path)
for cur_path, cur_dirs, cur_files in os.walk(path):
for name in cur_files:
file_path.append(os.path.join(cur_path[int(keynum):], name))
return file_path
if __name__ == '__main__':
path_left = r'D:\***'
path_right = r'D:\***'
left_path_files = left_right_path_file(path_left) # 源文件夹(左)下 所有文件相对路径
right_path_files = left_right_path_file(path_right) # 源文件夹(右)下 所有文件相对路径
same_path_file = set(left_path_files).intersection(set(right_path_files)) # 源文件夹(左右)下,相对路径且文件名相同
2. Beyond Compare 4,依次文本比较
def sta_main(path_left, path_right):
'''匹配同路径同名文件;遍历完成bcompare比对,生成html比对结果;读取html比对结果,整理成表格'''
bc_path = r'D:\Program Files\Beyond Compare 4' # 调用本地BCompare # ******* ----- ********
os.chdir(bc_path)
left_path_files = left_right_path_file(path_left) # 源文件夹(左)下 所有文件相对路径
right_path_files = left_right_path_file(path_right) # 源文件夹(右)下 所有文件相对路径
same_path_file = set(left_path_files).intersection(set(right_path_files)) # 源文件夹(左右)下,相对路径且文件名相同
kk = 1
for path_file in same_path_file:
print(path_file)
time.sleep(0.3)
left_path_file = path_left + '\\' + path_file
right_path_file = path_right + '\\' + path_file
compare_file = r'D:\文件夹内容相似度比对\bc.txt'
out_file = r'D:\文件夹内容相似度比对\%d.html' % kk
bcompare_file(compare_file, left_path_file, right_path_file, out_file)
先得安装Beyond Compare 4,其中bc.txt文本内容,以及文本比较结果(html),见下。
bc.txt内容:
text-report layout:summary options:display-mismatches,line-numbers output-to:"%3" output-options:wrap-word,html-color "%1" "%2"
文本比较html结果:
文本比较(T)
已产生: 2022/9/26 15:10:42
左边文件: F:\同路径同名文件内容比对\***\logic\af.go
右边文件: F:\同路径同名文件内容比对\***\logic\af.go
56 个相同行
1 个不重要的左边独有行
3 个不重要的差异行
3 个重要的左边独有行
10 个重要差异行
7 个差异部分
3. 汇总、统计结果