如图所示,有一批文本数据,包含学生的姓名,年龄,家乡学号以及格言,每项占一行,每名同学信息以空行隔开,现在想用python将其转换为如下形式:
import sys,os,string
def readvote(file_in,file_ou):
fp_in = open(file_in,'r')
fp_ou = open(file_ou,'w+')
flag = ["nam","age","hom","num","txt"]
str_ou = ""
for line in fp_in:
for i in range(0,len(flag)):
sub_flag = line[0:3]
if sub_flag == flag[i]:
str_i = line[4:len(line)].replace("\n",",")
str_ou = str_ou + str_i
str_ou = str_ou[0:(len(str_ou)-1)]
fp_ou.write(str_ou)
if name =='__main__':
path_in = r"d:\v0\student.txt"
path_ou = r"d:\v1\student_v.txt"
readvote(path_in,path_ou)
自己临时想的这个代码确实有很大的bug,也曾想过用字典来处理,但是字典的顺序是随机的,不适合处理。希望大神多多指教。谢谢