这里是你的通告内容

春生

Be humble, communicate clearly, and respect others.

员工系统

员工系统

需求

作业需求: 作业需求:
对⽤户输⼊的字符串进⾏解析,从⽂件中筛选出相应符合条件的结果集。

find name,age from staff_table where age > 22
find * from staff_table where dept = “IT”
find * from staff_table where enroll_data like “2013”
demo 1
find name,age from staff_table where age > 22(提示:name和age之间
只有⼀个逗号没有空格)
要求:从staff_table⽂件中,找出员⼯年龄在22岁以上的员⼯,将这些员⼯的姓
名,员⼯的年龄打印出来
find name,age from staff_table where age > 22
对⽤户输⼊字符串的解析流程:
1 读⽂件
2 将每⼀个员⼯的年龄与22进⾏⽐较
3 获取到员⼯年龄⼤于22的员⼯信息
4 从符合条件的员⼯信息中筛选出员⼯的姓名、年龄
demo 2:
find * from staff_table where dept = “IT”
需求:从staff_table ⽂件中找到IT部⻔的员⼯,并打印员⼯的所有信息
demo 3:
find * from staff_table where enroll_data like “2013”
需求:从staff_table⽂件中找到员⼯的⼊职时间是2013年的员⼯,并打印员⼯所
有的信息

2 添加员⼯信息(⽤户的⼿机号不允许重复) 添加员⼯信息(⽤户的⼿机号不允许重复)
add staff_table Mosson,18,13678789527,IT,2018-12-11
需求:
添加员⼯信息时,必须有员⼯名称(Mosson)、员⼯年龄(18)、员⼯⼿
机号(13678789527)、员⼯部⻔(IT)、员⼯⼊职时间(2018-12-11)
将这些信息追加到staff_table⽂件新的⼀⾏中,并插⼊这⼀⾏的id
注意:添加员⼯的时候不考虑异常情况即添加的时候按照姓名,年龄,⼿机号,
部分,⼊职时间 且每⼀条数据都包含员⼯的完整数据(姓名、年龄、⼿机号、部
⻔、⼊职时间)

3 删除员⼯信息(根据序号删除相应员⼯的信息) 删除员⼯信息(根据序号删除相应员⼯的信息)
del from staff_table where id = 10
需求:从staff_table中删除序号id为10的这⼀条员⼯的信息

4 修改员⼯信息(可以根据特殊条件修改员⼯信息) 修改员⼯信息(可以根据特殊条件修改员⼯信息)
demo 1
update staff_table set dept=“Market” where dept = “IT”
需求:将staff_table中dept为IT的修改成dept为Market
demo 2
update staff_table set age=25 where name = “Alex Li”
需求:将staff_table中⽤户名为Alex Li的⽤户的年龄改成25

代码

import os
DB_FILE = "staff.db"
COLUMNS = ['id','name','age','phone','dept','enroll_data']
#文件转换成字典
def db_load(db_file):
    data = {}
    for col in COLUMNS:
        data[col] = []
    # print(data)
    with open(db_file,'r',encoding="utf-8") as f:
        for line in f:
            id, name, age, phone, dept, enroll_data = line.split(',')
            data['id'].append(id)
            data['name'].append(name)
            data['age'].append(age)
            data['phone'].append(phone)
            data['dept'].append(dept)
            data['enroll_data'].append(enroll_data)
    return data
#字典保存成文件
def save_db():
    f = open("%s.new" %DB_FILE,"w",encoding="utf-8")
    for index,calse in enumerate(STAFF_DATA["id"]):
        row = []
        for col in COLUMNS:
            row.append(STAFF_DATA[col][index])
        f.write(",".join(row))
    f.close()
    os.replace("%s.new" %DB_FILE,DB_FILE)
STAFF_DATA = db_load(DB_FILE)
#查
def syntax_find(data_set,query_clause):
    filter_clause_tmp = query_clause.split("from")[0][4:].split(",")
    filter_clause = [i.strip() for i in filter_clause_tmp]
    if "*" in filter_clause[0]:
        print(data_set)
    else:
        data_record = []
        for res in data_set:
            record = []
            for clause in filter_clause:
                index = COLUMNS.index(clause)
                record.append(res[index])
            data_record.append(record)
        print(data_record)
    print(f"匹配了{len(data_set)}条结果")
#增
def syntax_add(data_set,query_clause):
    formulate_row_tmp = query_clause.split('staff_table')[1].strip()
    # print(formulate_row.split(","))
    new_id = str(len(STAFF_DATA["id"]) + 1)
    formulate_row = new_id + "," + formulate_row_tmp
    add_list = formulate_row.split(",")
    # print(add_list)
    for index,col in enumerate(COLUMNS):
        STAFF_DATA[col].append(add_list[index])
    print(STAFF_DATA)
    print(f"成功添加{add_list}")
#删
def syntax_del(data_set,clase):
    tmp_condition,tmp_val = clase.split("=")
    condition = tmp_condition.strip()
    val = tmp_val.strip()
    staff_id = data_set[0][0]
    index = STAFF_DATA["id"].index(staff_id)
    # print(index)
    for value in STAFF_DATA.values():
        value.pop(index)
    print(STAFF_DATA)
    print(f"成功删除{condition}={val}的一条数据")
#改
def syntax_update(data_set,query_clause):
    formulate_row = query_clause.split('set')[1].strip()
    if len(formulate_row)>1:
        clo_name,new_val = formulate_row.split('=')
        for match_row in data_set:
            staff_id = match_row[0]
            staff_id_index = STAFF_DATA["id"].index(staff_id)
            STAFF_DATA[clo_name][staff_id_index] = new_val
        print(STAFF_DATA)
        print(f"更新了{len(data_set)}条记录")
    else:
        print("语法错误")
#>
def op_gt(conditon,value):
    record_data = []
    for index,val in enumerate(STAFF_DATA[conditon]):
        if float(val) > float(value):
            record = []
            for col in COLUMNS:
                record.append(STAFF_DATA[col][index])
            record_data.append(record)
    print(record_data)
    return record_data
#<
def op_lt(conditon,value):
    record_data = []
    for index, val in enumerate(STAFF_DATA[conditon]):
        if float(val) < float(value):
            record = []
            for col in COLUMNS:
                record.append(STAFF_DATA[col][index])
            record_data.append(record)
    return record_data
#=
def op_eq(conditon,value):
    record_data = []
    # print(conditon,value)
    for index, val in enumerate(STAFF_DATA[conditon]):
        # print(val)
        if val == value.strip('"'):
            record = []
            for col in COLUMNS:
                record.append(STAFF_DATA[col][index])
            record_data.append(record)
    return record_data
#like
def op_like(conditon,value):
    record_data = []
    for index, val in enumerate(STAFF_DATA[conditon]):
        if value.strip('"') in val:
            # print(value)
            record = []
            for col in COLUMNS:
                record.append(STAFF_DATA[col][index])
            record_data.append(record)
    return record_data
#解析where
def syntax_where_parser(clase):
    operators = {
        ">":op_gt,
        "<":op_lt,
        "=":op_eq,
        "like":op_like
    }
    for op_key,op_func in operators.items():
        if op_key in clase:
            column,val = clase.split(op_key)
            # print(column,val)
            matched_data = op_func(column.strip(),val.strip())
            return matched_data
    else:
        print("语法错误")
#解析cmd
def syntax_parser(cmd):
    syntax_list = {
        "add":syntax_add,
        "update":syntax_update,
        "del":syntax_del,
        "find":syntax_find,
    }
    cmd_action = cmd.split()[0]

    if cmd_action in ("find","add","update","del"):
        if "where" in cmd:
            query_clase,where_clase = cmd.strip().split("where")
            matched_records = syntax_where_parser(where_clase)

            if cmd_action == "del":
                syntax_list[cmd_action](matched_records, where_clase.strip())
            else:
                syntax_list[cmd_action](matched_records, query_clase)

        else:
            matched_records = []
            for index,stadd_id in enumerate(STAFF_DATA["id"]):
                record = []
                for col in COLUMNS:
                    record.append(STAFF_DATA[col][index])
                matched_records.append(record)
            query_clase = cmd
        # if cmd_action in syntax_list:
            syntax_list[cmd_action](matched_records,query_clase)
#主函数
def main():
    while True:
        cmd = input("[staff_data]:").strip()
        if not cmd:continue
        syntax_parser(cmd)

main()
posted @ 2020-11-09 21:22  PythonAV  阅读(173)  评论(0编辑  收藏  举报