1. 两个txt文件通过某一字段关联 Wenyu’s Blog
背景 将两个txt文件通过两者共有的某一项进行关联,类似于数据库中的不同表通过id相关联。 txt1:#checkins(userID/venueID/time/offset) txt2:#pois(venueID/latitude/longtitude/words/country) 通过共有项venueID,将txt1的数据以及txt2的数据关联起来,写入一个新的文件txt3。 格式如userID/venueID/time/offset/latitude/longitude/words/country
思路 将txt2文件的venueID作为字典的key,然后将latitude,longtitude,words,country写入一个列表里作为字典的值。
比对txt1中的venueID,相同则直接将txt1的此行写入txt3,同时将字典中的venueID对应的值——latitude,longtitude,words,country写入txt3
代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 f1=open('f:\checkins.txt' ,'r' ) f2=open('f:\pois.txt' ,'r' ) fout=open('f:\dataset.txt' ,'a+' ) dicc=dict() for line in f2: line=line.strip().split('\t' ) values=[] latitude=line[1 ] longitutde=line[2 ] words=line[3 ] country=line[4 ] values.append(latitude) values.append(longitutde) values.append(words) values.append(country) dicc[line[0 ]]=values for line1 in f1: venueID=line1.split('\t' )[1 ] if (dicc.get(venueID) != None ): fout.write(line1.strip('\n' )+'\t' +dicc[venueID][0 ]+'\t' +dicc[venueID][1 ]+'\t' +dicc[venueID][2 ]+'\t' +dicc[venueID][3 ]) fout.write('\n' ) f1.close() f2.close() fout.close()