首页 > 代码库 > 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"))
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。