自己在写从文件循环读每个句子的时候出现问题
错误1:
f=open('/home/xbwang/Desktop/scen_test_sim.csv','r') while True:line=f.readline()if line==None:breaka=line.strip().split('","')[1:]if len(a) >= 10:flag = 0for i in range(10):flag = flag +1con = a[i]fl1 = open('/home/xbwang/Desktop/b.txt','a')fl1.write(con + '\n')if(flag == 10) :print(con)print(flag) f.close
错误2:
f=open('/home/xbwang/Desktop/all_vectors','r') while True :line=f.readline()if line == None : breaka=line.split()b=a[0]print(b)f1=open('/home/xbwang/Desktop/a.txt','a')f1.write(b+'\n')
用这两个代码读文件后,会发现命令行中循环一直没有中止,并且会发现,第一个少了最后一行最后一个“哦,谢谢”,第二个少了最后一个vector的最后一个坐标,导致只有99维。这两个错在一个地方,都是用line == None去判断循环是否结束,在python中没有这种写法。
正确写法有以下两种:
正确1:
f=open('/home/xingyuzhou/Desktop/scen_test_sim.csv','r') line=f.readline() while line:a=line.strip().split('","')[1:]if len(a) >= 10:flag = 0for i in range(10):flag = flag +1con = a[i]fl1 = open('/home/xingyuzhou/Desktop/b.txt','a')fl1.write(con + '\n')if(flag == 10) :print(con)print(flag)line=f.readline() f.close
正确2:
f = open('/home/xbwang/Desktop/otherscore.txt','r') for line in f:a = line[2:]b = a[:-5]print bf1 = open('/home/xbwang/Desktop/otherscore1.txt','a')f1.write(b+'\n')