首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

[D]python 文本读出的有关问题

2012-03-12 
[D]python 文本读出的问题文本里面的内容如下:JrId: 1JournalTitle: AADE editors journalMedAbbr: AADE

[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 还不是很熟悉,下面是我写的有问题的:

Python code
#!/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()


上面得出来的是每一行生成了一条insert:
insert into test (`JrId`) values (" 1")
insert into test (`JournalTitle`) values (" AADE editors' journal")
insert into test (`MedAbbr`) values (" AADE Ed J")
insert into test (`ISSN`) values (" 0160-6999")
insert into test (`ESSN`) values ("")
insert into test (`IsoAbbr`) values (" AADE Ed J")
insert into test (`NlmId`) values (" 7708172")
…………
…………
…………
而我想要的是
insert into (JrId,JournalTitle,MedAbbr,ISSN,ESSN,IsoAbbr,NlmId) values("1"," AADE editors' journal"," AADE Ed J"," 0160-6999",""," AADE Ed J"," 7708172")
…………
…………
…………

想半天还是不知道如何实现。。麻烦高人指点下。


------------------------------
Double行动:
原帖分数:100
加分:100


[解决办法]
只要你文本文档格式都是7个一组,这个脚本可以读任意多组
Python code
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
[解决办法]
Python code
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() 

热点排行