[D]python 文本读出的问题
文本里面的内容如下:
JrId: 1
JournalTitle: AADE editors' journal
MedAbbr: AADE Ed J
ISSN: 0160-6999
ESSN:
IsoAbbr: AADE Ed J
NlmId: 7708172
JrId: 2
JournalTitle: AANA journal
MedAbbr: AANA J
ISSN: 0094-6354
ESSN:
IsoAbbr: AANA J
NlmId: 0431420
JrId: 3
JournalTitle: AARN news letter
MedAbbr: AARN News Lett
ISSN: 0001-0197
ESSN:
IsoAbbr: AARN News Lett
NlmId: 1251052
上面的文本我想插入到数据库里面,(7行一组)故想生成:
insert into (JrId,JournalTitle,MedAbbr,ISSN,ESSN,IsoAbbr,NlmId) values(%.....)
刚接触python 还不是很熟悉,下面是我写的有问题的:
#!/usr/bin/pythonj=open('J_Entrez1.txt')while True: t=j.readline().strip().split(':') if not t: break col,value = t query = "insert into test (`%s`) values (%s)" %(col,'"'+value+'"') print queryj.close()
lines = open('J_Entrez1.txt').readlines()ind = -1cnt = 0for line in lines: if cnt%7==0: ind += 1 exec('dic'+str(ind)+'={}') exec('dic'+str(ind)+'[line.strip().split(":")[0]]=line.strip().split(":")[1].strip()') cnt += 1for i in range(ind+1): print '+++++NEW LINE++++++++++++++++++' first = 'insert into (' last = ') values(' for key in eval('dic'+str(i)+'.keys()'): first += key+',' last += '"'+eval('dic'+str(i)+'[key]')+'",' query = first[:-1]+last[:-1]+')' print query
[解决办法]
fin = open('in.txt','r')fout = open('out.txt','w')i=0out = 'insert into ('values = ')values('for line in fin.readlines(): print line content = line.split(':') if i % 7 == 6: out+=content[0].strip() values+='"' + content[1].strip() + '"' fout.write(out+values+')\n') print i out = 'insert into (' values = ')values(' else: out +=content[0].strip()+',' values+='"' + content[1].strip() + '"' + ',' i+=1fin.close()fout.close()