首页 > 代码库 > python读取文本、配对、插入数据脚本

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

#-*- coding:UTF-8 -*-
#-*- author:Zahoor Wang -*-
 
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", ‘\n‘, ‘\t‘)
ts = parse("./teacher.txt", ‘\r\n‘, ‘ ‘)
for s in parse("./student.txt", ‘\r\n‘, ‘ ‘):
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, "\r\n"))