'''
查找A文件中,与B文件中内容不重复的内容
'''
import sys
import os
'''
字符串查找函数,使用二分查找法在列表中进行查询
'''
def binarySearch(value, lines):
right = len(lines) - 1
left = 0
a = value.strip()
while left <= right:
middle = int((right + left + 1)/2)
b = lines[middle].strip()
if a == b:
return 1
if a < b:
right = middle - 1
else:
left = middle + 1
return 0
DPT = 100000
fileAName = sys.argv[1];
fileBName = sys.argv[2];
print("拆分比对文件...\n")
fB = open(fileBName)
tempFileNo = 1
tempFileName = "temp{0}".format(tempFileNo)
fTemp = open(tempFileName, "w+")
line = fB.readline()
lineCount = 0
while line:
if lineCount >= DPT:
fTemp.flush()
fTemp.close()
tempFileNo = tempFileNo + 1
tempFileName = "temp{0}".format(tempFileNo)
fTemp = open(tempFileName, "w+")
lineCount = 0
fTemp.write(line)
lineCount = lineCount + 1
line = fB.readline()
fTemp.flush()
fTemp.close()
fB.close()
print("拆分完成,一共{0}个临时文件,{1}条数据。\n".format(tempFileNo, (tempFileNo-1)*DPT + lineCount))
fA = open(fileAName)
resultTempFile = {"result0", "result1"};
tempIndex = 0
fOut = open("repeat", "w+")
repeatCount = 0
for i in range(1, tempFileNo + 1):
print("比较第{0}个临时文件...\n".format(i))
if 0 == tempIndex:
resultTempFile = "result0"
tempIndex = 1
else:
resultTempFile = "result1"
tempIndex = 0
fResult = open(resultTempFile, "w+")
fTemp = open("temp{0}".format(i))
lineSet = fTemp.readlines()
fTemp.close()
lineList = list(lineSet)
lineList.sort()
line = fA.readline()
while line:
if 0 == binarySearch(line, lineList):
fResult.write(line)
else:
fOut.write(line)
repeatCount = repeatCount + 1
line = fA.readline()
fA.close()
fResult.flush()
fResult.close()
fA = open(resultTempFile)
fA.close()
fOut.flush()
fOut.close()
print("比较完成,重复数据{0}条".format(repeatCount))
os.rename(resultTempFile, "result")
print("删除临时文件...\n")
while tempFileNo > 0:
tempFileName = "temp{0}".format(tempFileNo)
os.remove(tempFileName)
tempFileNo = tempFileNo - 1
print("脚本结束。\n")