python读取文本、配对、插入数据脚本

#在工作中遇见了一个处理数据的问题,纠结了很久,写下记录一下。
#-*- coding:UTF-8 -*- #-*- author:ytxu -*- import codecs, os, sys, platform, string def env(): return platform.system() def read_file(uri, charset = "utf-8"): f = codecs.open(uri, "r", charset) s = f.read() f.close() return s def write_file(uri, content = u"", charset = "utf-8"): f = codecs.open(uri, "w", charset) f.write(content) f.close() def parse(f, osep, ls): ctx = read_file(f) r = [] for l in ctx.split(osep): tl = [] for c in l.split(ls): c = c.strip() len(c) > 0 and tl.append(c) r.append(tuple(tl)) return r def parse_log(f, osep, ls): ctx = read_file(f) r = [] for l in ctx.split(osep): tl = [] for c in l.split(ls): c = c.strip() tl.append(c) r.append(tuple(tl)) return r def found_t(ts, n): for t in ts: if t[0].rfind(n) != -1: return t def found_id(us, n): for u in us: if (len(u) < 2): break if (u[1].rfind(n) != -1) or (u[2].rfind(n) != -1) or (u[3].rfind(n) != -1): return u[0] return None if __name__ == '__main__': env() == "Windows" and os.system("cls") rst = [] us = parse_log("./user.txt", ' ', ' ') ts = parse("./teacher.txt", ' ', ' ') for s in parse("./student.txt", ' ', ' '): t = found_t(ts, s[5]) if t is None: print s[5] continue sid = found_id(us, s[4]) tid = found_id(us, t[2]) if sid is not None and tid is not None: q = u"INSERT into student_teacher_relation(student_id,teacher_id,subject) values (%d,%d,'%s')" %(int(sid),int(tid),t[1]) # print sid, tid, q rst.append(q) # print u"学生帐号:", s[4], u"学生名称:", s[0], u"代课老师:", t[0], u"代课老师的帐号:", t[2] write_file("./insert.sql", string.join(rst, " "))

  

原文地址:https://www.cnblogs.com/Mushishi_xu/p/3729484.html