python开发基础----函数(作业综合练习)

有以下员工信息表

现需要对这个员工信息文件,实现增删改查操作

  1. 可进行模糊查询,语法至少支持下面3种:
    1.   select name,age from staff_table where age > 22
    2.   select  * from staff_table where dept = "IT"
    3.       select  * from staff_table where enroll_date like "2013"
    4. 查到的信息,打印后,最后面还要显示查到的条数 
  2. 可创建新员工纪录,以phone做唯一键,staff_id需自增
  3. 可删除指定员工信息纪录,输入员工id,即可删除
  4. 可修改员工信息,语法如下:
    1.   UPDATE staff_table SET dept="Market" WHERE where dept = "IT"

 注意:以上需求,要充分使用函数,请尽你的最大限度来减少重复代码!

staff_table = [
    {
        'staff_id' : 1,
        'name' : 'Alex Li',
        'age' :  22,
        'phone' : '13651054608',
        'dept' : 'IT',
        'enroll_date' : '2013-04-11'
    },
    {
        'staff_id': 2,
        'name': 'Jack Wang',
        'age': 30,
        'phone': '13304320533',
        'dept': 'HR',
        'enroll_date': '2015-05-03'
    },
    {
        'staff_id': 3,
        'name': 'Rain Liu',
        'age': 25,
        'phone': '13786324608',
        'dept': 'Sales',
        'enroll_date': '2016-04-11'
    },
    {
        'staff_id': 4,
        'name': 'Mack Cao',
        'age': 40,
        'phone': '13739214608',
        'dept': 'IT',
        'enroll_date': '2009-01-11'
    },
]


def select(column):
    x = column[1].split('WHERE')
    if len(x) > 1:
        if x[1].strip()[0:8] == 'staff_id':
            if x[1].find("=") != -1 and x[-1].find(">") != -1:
                return operate(x[1], '>=', x[0],"select",column=column[0])
            elif x[1].find("=") != -1 and x[-1].find("<") != -1:
                return operate(x[1], '<=', x[0],"select",column=column[0])
            elif x[1].find("=") != -1:
                return operate(x[1], '=', x[0],"select",column=column[0])
            elif x[1].find(">") != -1:
                return operate(x[1], '>', x[0],"select",column=column[0])
            elif x[1].find("<") != -1:
                return operate(x[1], '<', x[0],"select",column=column[0])
            else:
                return False, "操作符有误!"
        else:
            if x[1].find("=") == -1:
                return False, "操作符错误!"
            else:
                return operate(x[1], '=', x[0],"select", False,column=column[0])
    else:
        func = lambda z,k:[z[i] for i in k ]
        x = column[0].split(" ")
        if x[1]== "*":
            for i in staff_table:
                print(i)
        else:
            x = x[1].split(",")
            for i in staff_table:
                print(func(i,x))


        return True, len(staff_table)
def insert(phone,name=None,age=None,dept=None,enroll_date=None,func=lambda x,phone:phone != x['phone']):
    '''
    增加一条记录
    :param phone: 增加记录phone值,值要是唯一的
    :param name: 增加记录name值
    :param age: 增加记录age值
    :param dept: 增加记录dept值
    :param enroll_date: 增加记录enroll_date值
    :param func:  查找传入的phone是否已存在,如果不存在就添加记录,staff_id的值自增一
    :return:  返回True为添加成功,否则添加失败
    '''
    phone_is = []
    for i in staff_table:
        phone_is.append(func(i,phone))

    if all(phone_is):
        staff_table.append({
            'staff_id': max(staff_table,key=lambda x:x['staff_id'])['staff_id'] + 1,
            'name' : name,
            'age' : age,
            'phone' : phone,
            'dept': dept,
            'enroll_date' : enroll_date
        })
        return True
    else:
        return False

def delete(id,func=lambda dic,id: dic['staff_id']==int(id)):
    '''
    删除某条记录
    :param id: 删除指定记录id,也就是字典里面的staff_id号
    :param func: 根据id查找字典对应的记录,然后删除
    :return:   返回True是删除成功,False为删除失败
    '''
    person = ''
    for i in  staff_table:
        if func(i,id):
            person = staff_table.pop(staff_table.index(i))
    if person:
        return True
    else:
        return False



def update(kwargs1):
    '''
    更改某条记录
    :param func:     查找条件的函数
    :param kwargs1:  需要修改的字段和值
    :param kwargs2:  判断条件,默认不加条件
    :return: 返回Ture为修改成功,False为修改失败
    '''
    x = kwargs1.split('WHERE')
    if len(x) > 1:
        if x[1].strip()[0:8] == 'staff_id':
            if x[1].find("=") != -1 and x[-1].find(">") != -1:
                return operate(x[1],'>=',x[0])
            elif x[1].find("=") != -1 and x[-1].find("<") !=-1:
                return operate(x[1],'<=',x[0])
            elif x[1].find("=") != -1:
                return operate(x[1],'=',x[0])
            elif x[1].find(">") != -1:
                return operate(x[1],'>',x[0])
            elif x[1].find("<") != -1:
                return operate(x[1],'<',x[0])
            else:
                return False,"操作符有误!"
        else:
            if x[1].find("=") == -1 :
                return False,"操作符错误!"
            else:
                return operate(x[1],'=',x[0],False)
    else:
        keys_value = x[0].split('=')
        num = 0
        func = lambda z:z[1] if z[1].find('"') == -1 else z[1].split('"')[1].strip()
        keys_value[1] = func(keys_value)
        for i in staff_table:
            if keys_value[0].strip() in i :
                i[keys_value[0].strip()] = keys_value[1]
                num += 1
        return True,num

def operate(term,operator,x=None,op="update",is_int=True,column=None):
    '''

    :param term: 传入WHERE后面那部分条件字符串
    :param operator:  传入操作符
    :param is_int: 是否为整数
    :return:
    '''
    key, value = term.split(operator)
    key = key.strip()
    if value.find('"') != -1:
        value = value.split('"')[1]
    if operator == "=":
        if is_int:
            func = lambda z, key, value: z[key] == int(value)
        else:
            func = lambda z, key, value: z[key] == value
    elif operator == ">":
        func = lambda z, key, value: z[key] > int(value)
    elif operator == ">=":
        func = lambda z, key, value: z[key] >= int(value)
    elif operator == "<":
        func = lambda z, key, value: z[key] < int(value)
    elif operator == "<=":
        func = lambda z, key, value: z[key] <= int(value)
    num = 0

    if op == "update":
        u_key, u_value = x.split("=")
        u_key = u_key.strip()
        if u_value.find('"') != -1:
            u_value = u_value.split('"')[1]
        for i in staff_table:
            if func(i, key, value):
                i[u_key] = u_value
                num += 1
    elif op == "select":
        func1 = lambda z, k: [z[i] for i in k]
        x = column.split(" ")
        if x[1] == "*":
            for i in staff_table:
                if func(i, key, value):
                    print(i)
                    num += 1
        else:
            x = x[1].split(",")
            for i in staff_table:
                if func(i, key, value):
                    print(func1(i, x))
                    num += 1


    return True, num



# id = input("请输入员工的id:")
# delete(id,lambda dic,id: dic['staff_id']==int(id))
# insert('18721331234')
EFUNC = {
        'delete':delete,
        'select':select,
         'insert':insert,
         'update':update,
         }

message = '''请选择你的操作方式:
1 查询记录(如 select  name,age from staff_tab where staff_id > 2)
2 删除记录
3 修改记录 (如update staff_tab set name="xieys" where name = "alex")
4 添加记录
q 退出
'''


while True:
    choise = input(message)
    if choise.strip()[0] == '1':
        statement = input('请输入修改语句(语法:select name,age from staff_tab WHERE staff_id > 2:')
        statement = statement.split("from")
        if statement[1].split(" ")[1] == "staff_tab":
            result,num = EFUNC['select'](statement)
            if result:
                print("一共找到%s条记录!" % num)
        else:
            print("没有此表!")

    elif choise.strip()[0] == '2':
        id = input("请输入要删除记录的id号:")
        if EFUNC["delete"]:
            print("删除成功!")
        else:
            print("删除失败!")
    elif choise.strip()[0] == '3':
        statement = input('请输入修改语句(语法:update 表格 set 字段 = "值" WHERE 字段 = "值"):')
        statement = statement.split('set')

        if statement[0].strip() == "update staff_tab" :
            result,num = EFUNC["update"](statement[1])
            if result:
                print("一共修改了%s条记录!" % num)
        else:
            print("没有此表格!")

    elif choise.strip()[0] == '4':
        name = input("请输入姓名:")
        age = input("请输入年龄:")
        phone = input("请输入电话:")
        dept = input("请输入职业:")
        enroll_date = input("请输入入职日期:")
        if EFUNC["insert"](phone,name,age,dept,enroll_date):
            print("添加成功")
        else:
            print("添加失败")

    elif choise.strip()[0] == 'q':
        break
View Code

 

posted @ 2019-09-09 15:04  Mr-谢  阅读(158)  评论(0)    收藏  举报