有关系A和B的文件,其中A-->B,B有可能也是A的成员,寻找一个tree,如果B已经到达最顶层,那么A-->B为正确的映射关系,如果出现循环则记录这些错误,和key的最终指向
#-*-coding:UTF-8-*- #!/usr/bin/env python __author__ = 'chao.zhang.sh' import threading class Mapping(): def __init__(self): self.Mapping={} self.LastMerge={} self.keys=None def Search(self): try: DataFile=open('mapping.csv','r') DataWrite=open('Result/mappingResult.csv','w') DataWriteCircle=open('Result/mappingResultWrong.csv','a') A=[] B=[] DataFile.next() for temp in DataFile: data=temp.decode("utf-8").strip().split("\t") self.Mapping[data[1]]=data[2] A.append(data[1]) B.append(data[2]) self.keys=self.Mapping.keys() for temp in (set(B).difference(set(A)))://求第二列和第一列的差集 self.Mapping[temp]=int(-1)//将差集全部置-1 print len(self.Mapping) i=0 for key in self.keys: i+=1 j=0 Keys=[key] while True: if int(self.Mapping[Keys[-1]])==int(-1)://遇到-1,证明已经找到树顶部 DataWrite.write("\t".join([key,Keys[-1]]).encode("utf-8")+"\n") break//跳出while循环 else: if self.Mapping[Keys[-1]] in Keys://遇到新的key值出现在keys列表中,证明出现了循环,记录错误数据 DataWriteCircle.write("\t".join(Keys).encode("utf-8")+"\n") break Keys.append(self.Mapping[Keys[-1]]) print "key:%s newKey:%s"%(key,Keys[-1]) print i except Exception as err: print err finally: DataFile.close() DataWrite.flush() DataWrite.close() DataWriteCircle.flush() DataWriteCircle.close() if "__main__"==__name__: A=Mapping() A.Search()