python筛选出两个文件中重复行的方法
2018-05-31 11:10
986 查看
本文实例为大家分享了python脚本筛选出两个文件中重复的行数,供大家参考,具体内容如下
''' 查找A文件中,与B文件中内容不重复的内容 ''' #!usr/bin/python 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 # DPT 是Data Per File的意思 fileAName = sys.argv[1]; fileBName = sys.argv[2]; #STEP1:先拆掉B文件,作为比较基准,临时文件命名为temp1,temp2,...,tempN 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)) #STEP2:把A文件与B文件拆出来的临时文件逐个进行比较,将结果轮流写入文件result0, result1 # 最后写入的result文件就是最终结果 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") #STEP3:结束后把临时文件都删掉 print("删除临时文件...\n") while tempFileNo > 0: tempFileName = "temp{0}".format(tempFileNo) os.remove(tempFileName) tempFileNo = tempFileNo - 1 print("脚本结束。\n")
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章推荐
- 用Python实现筛选文件脚本的方法
- python 一个简单的依靠文件来判断key是否重复的方法
- 使用python读取txt文件的内容,并删除重复的行数方法
- Python实现求两个csv文件交集的方法
- Python实现连接两个无规则列表后删除重复元素并升序排序的方法
- python脚本,筛出两个文件中重复的行
- python对比两个文件的方法
- Python过滤txt文件内重复内容的方法
- python删除本地夹里重复文件的方法
- Mod_python 访问时不访问特定py文件的配置方法
- 【转】Windows下用Python你会几种copy文件的方法?
- C#播放声音的两个方法 + 流读写文件
- 显示两个文件不一致的内容的实现(细胞分裂的方法)
- Python:查找硬盘上重复文件
- XML文件操作的两个方法
- “class”类型重定义 || 防止头文件重复加载 || 两个类之间互相引用
- Python 文件对象的方法
- Python学习笔记-XML大文件的XSD验证方法
- flex 3.0中关于两个.mxml文件之间链接的简单方法
- 移除ArrayList内重复数据的两个方法