python映射关系

有关系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()
  

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值