【Python】两个txt文件通过某一字段关联

背景

将两个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

代码

f1=open('f:\checkins.txt','r')
f2=open('f:\pois.txt','r')
fout=open('f:\dataset.txt','a+')

dicc=dict()
for line in f2: #将pois.txt截取出各个字段,写入字典中,key为venueID,value为[latitude,longitutde,words,country]
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 #venueID:[latitude,longitutde,words,country]
#venueID_list=[]

for line1 in f1:
venueID=line1.split('\t')[1]

if(dicc.get(venueID) != None):
#if(venueID not in venueID_list): #去掉重复,不需要则注释掉
#venueID_list.append(venueID)

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()