Python员工信息作业

2023-11-03

作业简介:

  • 根据用户输入,来实现增删改查,处理员工信息数据。

1、信息格式:
信息
2.文本数据:

1,Alex Li,22,13651054608,IT,2013-04-01
2,Jack Wang,28,13451024608,HR,2015-01-07
3,Rain Wang,21,13451054608,IT,2017-04-01
4,Mack Qiao,44,15653354208,Sales,2016-02-01
5,Rachel Chen,23,13351024606,IT,2013-03-16
6,Eric Liu,19,18531054602,Marketing,2012-12-01
7,Chao Zhang,21,13235324334,Administration,2011-08-08
8,Kevin Chen,22,13151054603,Sales,2013-04-01
9,Shit Wen,20,13351024602,IT,2017-07-03
10,Shanshan Du,26,13698424612,Operation,2017-07-02

3.作业需求:
1 查⽂件((find)):

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"

2 添加员⼯信息(⽤户的⼿机号不允许重复) 添加员⼯信息(⽤户的⼿机号不允许重复)

>>>:add staff_table Mosson,18,13678789527,IT,2018-12-11

3 删除员⼯信息(根据序号删除相应员⼯的信息) 删除员⼯信息(根据序号删除相应员⼯的信息)

>>>:del from staff_table where id = 10
需求:从staff_table中删除序号id为10的这⼀条员⼯的信息

4 修改员⼯信息(可以根据特殊条件修改员⼯信息) 修改员⼯信息(可以根据特殊条件修改员⼯信息)

>>>:update staff_table set dept=“Market” where dept = "IT"
需求:将staff_table中dept为IT的修改成dept为 Market

4.写README.md文档:

  • pycharm就可以写md文档了

readmd

5.主体函数目录:

main()  # 主函数入口,让用户输入指令
|-input_processing(cmd)  # 指令解析函数,解析完成后分发给以下对应的处理函数
    |-add_data(add_cmd)  # 处理新增操作
    |-del_data(del_cmd)  # 处理删除操作
    |-update_data(update_cmd)  # 处理修改操作
    |-find_data(from_cmd)  # 处理查询操作,分为四种情况 (> < = like)
        |-greater_fac(left_cmd, right_cmd)  # 查询大于
        |-small_fac(left_cmd, right_cmd)  # 查询小于
        |-equal_fac(left_cmd, right_cmd)  # 查询等于
        |-like_fac(left_cmd, right_cmd)  # 查询like

6.思维导图:

在这里插入图片描述

7.支持的指令:

支持以下指令:

  • 增: add staff_table Mosson,18,13678789527,IT,2018-12-11
  • 删: del from staff_table where id = 10
  • 改: update staff_table set dept="Market" where dept = "IT"
  • 查: find name,age from staff_table where age > 22

8.项目主体思路:

  • 1.运行主函数mian(),让用户输入如果输入为空,continue
  • 2.如果用户输入指令不为空,将指令(cmd)传入input_processing(cmd)函数,进入函数继续下一步
  • 3.如果指令正确,执行对应的函数进行数据的清洗工作,否则提示指令错误
  • 4.清洗完数据结束后将结果返回给用户
  • 5.用户操作结束后,输入q退出程序

9.项目源码:

#!/usr/bin/python
# -*- coding:utf-8 -*-
# Python就业班:HuangPei
# datetime:20201203

# TXT数据路径
data_file = './staff_table.txt'

# 数据头目格式
name_index = ['id', 'name', 'age', 'phone', 'dept', 'enrolled_date']


# 从TXT获取数据,并整理数据格式
def read_data(file_path):
    """
    读取数据表到内存,
    :param file_path:传入文件
    :return:
    """
    data = []
    with open(file_path, mode='r', encoding='utf-8') as f:
        for i in f.readlines():  # 将数据以列表的形式存到data中
            data.append(dict(zip(name_index, i.strip().split(','))))
            # print(dict(zip(name_index, i.strip().split(','))))
            # print(list(zip(name_index, i.strip().split(','))))

    return data


# 整理好的TXT数据
DATA = read_data(data_file)


# 返回大于数据
def greater_fac(left_cmd, right_cmd):
    """
    返回大于的数据
    :return:
    """
    for i in DATA:
        if left_cmd[0] == '*':
            print(i['id'], i['name'], i['age'], i['phone'], i['dept'], i['enrolled_date'])
        elif len(left_cmd) == 1 and left_cmd[0].isalpha():
            if int(i['age']) > int(right_cmd):
                print(i[left_cmd[0]])
        elif len(left_cmd) == 2:
            if int(i[left_cmd[1]]) > int(right_cmd):
                print(i[left_cmd[0]], i[left_cmd[1]])
        elif len(left_cmd) == 3:
            if int(i[left_cmd[1]]) > int(right_cmd):
                print(i[left_cmd[0]], i[left_cmd[1]], i[left_cmd[2]])
        elif len(left_cmd) == 4:
            if int(i[left_cmd[1]]) > int(right_cmd):
                print(i[left_cmd[0]], i[left_cmd[1]], i[left_cmd[2]], i[left_cmd[3]])
        elif len(left_cmd) == 5:
            if int(i[left_cmd[1]]) > int(right_cmd):
                print(i[left_cmd[0]], i[left_cmd[1]], i[left_cmd[2]], i[left_cmd[3]], i[left_cmd[4]])
        else:
            print('请检查查询字段!!')
    else:
        print('结果输出完成~~')
    # print("这是大于", left_cmd, right_cmd)


# 返回小于数据
def small_fac(left_cmd, right_cmd):
    """
    返回小于的数据
    :return:
    """
    # print("这是小于", len(left_cmd), left_cmd, right_cmd)
    for i in DATA:
        if left_cmd[0] == '*':
            print(i['id'], i['name'], i['age'], i['phone'], i['dept'], i['enrolled_date'])
        elif len(left_cmd) == 1 and left_cmd[0].isalpha():
            if int(i['age']) < int(right_cmd):
                print(i[left_cmd[0]])
        elif len(left_cmd) == 2:
            if int(i[left_cmd[1]]) < int(right_cmd):
                print(i[left_cmd[0]], i[left_cmd[1]])
        elif len(left_cmd) == 3:
            if int(i[left_cmd[1]]) < int(right_cmd):
                print(i[left_cmd[0]], i[left_cmd[1]], i[left_cmd[2]])
        elif len(left_cmd) == 4:
            if int(i[left_cmd[1]]) < int(right_cmd):
                print(i[left_cmd[0]], i[left_cmd[1]], i[left_cmd[2]], i[left_cmd[3]])
        elif len(left_cmd) == 5:
            if int(i[left_cmd[1]]) < int(right_cmd):
                print(i[left_cmd[0]], i[left_cmd[1]], i[left_cmd[2]], i[left_cmd[3]], i[left_cmd[4]])
        else:
            print('字段错误,请检查查询字段。')
    else:
        print('结果输出完成!')


# 返回等于数据
def equal_fac(left_cmd, right_cmd):
    """
    返回等于的数据
    :return:
    """
    new_name = right_cmd.replace('"', " ").strip()
    print(new_name)

    for i in DATA:
        if left_cmd[0] == '*' and new_name in i['dept']:
            print(i['id'], i['name'], i['age'], i['phone'], i['dept'], i['enrolled_date'])


# 返回like数据
def like_fac(left_cmd, right_cmd):
    """
    返回值里对应的数据
    :return:
    """
    # print(right_cmd)
    new_name = right_cmd.replace('"', " ").strip()
    for like_data in DATA:
        if new_name in like_data['enrolled_date']:
            print(like_data['id'], like_data['name'], like_data['age'], like_data['phone'], like_data['dept'],
                  like_data['enrolled_date'])
    else:
        print('查询结果输出完成!')


# 处理查询
def find_data(from_cmd):
    """
    处理指令返回数据
    :param from_cmd:
    :return:
    """
    msg = """
        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"
    """

    # 转成:['name,age', ...., 'age', '>', '22']
    deal_with = from_cmd.split()[1:]
    # print(deal_with)

    new_cmd = ' '.join(deal_with)
    symbol_list = ['>', '<', '=', 'like']

    # 如果 符号在列表中 根据索引分割 指令
    for symbol in symbol_list:
        if symbol in new_cmd:
            left, right = new_cmd.split(symbol)
            # print(list(t.split()),l)
            new_left = list(left.split())  # ['name', 'age']
            count_name = new_left[0].split(',')
            # print(i, 55555555555)
            # break

            # 定义一个字典,值对应一个函数,如果符号在key中,执行对应的函数
            exe_fac = {
                '>': greater_fac,
                '<': small_fac,
                '=': equal_fac,
                'like': like_fac,
            }
            # print(exe_fac, '-----------')

            # 判断符号是否在字典的key中
            if symbol in exe_fac:
                # print(symbol, 'zhess ')
                exe_fac[symbol](count_name, right)  # 调用字典里的函数
            break
    else:
        print('语法错误!!!只支持示例指令:%s' % msg)


# 处理新增
def add_data(add_cmd):
    """
    新增用户信息
    :param add_cmd:
    :return:
    """
    msg = 'add staff_table Mosson,18,13678789527,IT,2018-12-11'

    # 判断 staff_table 是否在指令中
    if 'staff_table' in add_cmd:
        # print(add_cmd)
        read_data(data_file)

        # 拆分为:['Mosson', '18', '13678789527', 'IT', '2018-12-11']
        refactoring_name = add_cmd.strip().split()[2:]
        new_name = ''.join(refactoring_name).split(',')
        # print(new_name)

        # 获取序号 进行自增
        id_number = []
        for i in DATA:
            id_number.append(int(i['id']))
        new_id = (max(id_number) + 1)

        new_data = ','.join(new_name)
        with open(data_file, 'a+') as f:
            f.write(str(new_id) + ',' + new_data + '\r')
            f.close()

        print('信息添加成功:id:%s %s' % (new_id, new_data))

    else:
        print('add:语法错误!!支持以下指令:%s' % msg)


# 处理删除
def del_data(del_cmd):
    """
    删除用户信息
    :param del_cmd:
    :return:
    """
    msg = 'del from staff_table where id = 10'

    # 如果 from 和 where 在指令中
    if 'from' and 'where' in del_cmd:
        # print(del_cmd)

        # 分割为:del from staff_table where id   9
        left_name, right_name = del_cmd.split('=')
        # print(left_name, right_name)

        # 清空后写入
        new_file = open(data_file, mode='r+')
        new_file.truncate()
        new_file.close()

        for i in DATA:
            new_data = ','.join(i.values())  # 转换DATA里的数据
            if int(right_name) != int(i['id']):  # 这里是找出ID不相等,然后写入文件。

                with open(data_file, mode='a+') as f:
                    f.write(new_data + '\r')
        else:
            print('成功删除id:%s 的信息~' % right_name)
    else:
        print("del:语法错误!!支持以下指令:%s" % msg)


# 处理修改
def update_data(update_cmd):
    """
    修改员工信息函数
    :param update_cmd:
    :return:
    """
    # left_name: age
    # left_data: 25
    # right_name: name
    # right_data: "Alex Li"
    # 左边25,右边Alex Li

    # update staff_table set dept="Market" where dept = "IT"
    # update staff_table set age=25 where name = "Alex Li"

    msg = ',update staff_table set dept="Market" where dept = "IT"'

    # 判断 set 和 where 是否在指令中
    if 'set' and 'where' in update_cmd:
        left_cmd, right_cmd = update_cmd.strip().split('where')
        # print(left_cmd, right_cmd)

        # 分割成 l:update staff_table   r:dept="Market"
        new_left, new_right = left_cmd.strip().split('set')
        # print(new_left, new_right)

        # 左边转成:left_name: dept left_data: "Market"
        left_name, left_data = new_right.strip().split('=')
        # print("left_name:",left_name, "left_data:", left_data)

        # 右边转成:right_name: dept  right_data:  "IT"
        right_name, right_data = right_cmd.strip().split('=')
        # print("right_name:", right_name, "right_data:", right_data)

        # 把 即将修改数据的 双引号改成单引号
        new_left_data = left_data.replace('"', " ").strip()
        new_right_data = right_data.replace('"', " ").strip()
        # print('左边%s,右边%s' % (new_left_data, new_right_data))

        # 清空操作
        clear_file = open(data_file, mode='r+')
        clear_file.truncate()
        clear_file.close()

        for i in DATA:
            # 例如:如果名字在列表中,将包含名字项的age改成25
            if new_right_data in i[right_name.strip()]:
                # 修改内容
                i[left_name.strip()] = new_left_data
                print("成功将%s的%s修改为%s" % (right_data, left_name, new_left_data))
                # i[right_name.strip()].replace(new_right_data,new_left_data )
            data = ','.join(i.values())
            with open(data_file, mode='a+') as f:
                f.write(data + '\r')

        else:
            print('修改完成!!')

    else:
        print('update:语法错误!支持以下指令:%s' % msg)


# 处理用户输入
def input_processing(cmd):
    """
    处理用户输入
    :param cmd:
    :return:
    """
    # :find name,age from staff_table where age > 22
    symbol = ['find', 'add', 'del', 'update']

    # 取第0个数据进行查找,是否存在于symbol,如果在,执行对应的函数
    if cmd.split()[0] in symbol:
        if cmd.split()[0] == 'find':
            print('find')
            find_data(cmd)
        if cmd.split()[0] == 'add':
            print('add')
            add_data(cmd)
        if cmd.split()[0] == 'del':
            print('del')
            del_data(cmd)
        if cmd.split()[0] == 'update':
            print('update')
            update_data(cmd)
    else:
        print("语法错误!!")


# 主函数,让用户一直输入
def main():
    """
    主函数入口
    :return:
    """
    while True:
        user_input = input(">>>>>:")
        if user_input == 'q': quit()
        if not user_input:
            print('指令不能为空!!')
            continue
        input_processing(user_input)


# 执行主函数
main()

总结:

这个作业是对第二章和前面学习内容的综合,也算是自己写的比较多的代码了。这个作业还有很多优化的地方,分享给 小伙伴们看看,希望能帮助到你们。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python员工信息作业 的相关文章

随机推荐

  • Unity把png图片转换为sprite格式

    最近自己在做游戏项目 经常碰到导入的图片是png格式 但是要转换为sprite格式才能应用 以下是转换的简单方式 不需要代码的 1选中要转换的png图片 在Inspector窗口查看属性 2在窗口中找到Texture Type选择Sprit
  • Java程序员项目面试

    如何做自我介绍 自我介绍该怎么做 要介绍什么 自我介绍尽可能控制在3分钟以内 关于技术介绍以外例如 性格 爱好等尽可能忽略 自我介绍时应该主要包含下面几个内容 个人信息 15秒 学习经历 30秒 工作经历 2分钟 其中社招工作经历最为重要
  • Python 根据Excel修改文件名称 封装成.exe程序

    目录 前言 一 实验环境 二 实现步骤 1 设计思路 2 引入库 3 具体代码 4 封装成exe程序 5 功能展示 总结 前言 公司想要一个可以在任何一个Windows电脑上能使用的工具 可以根据Excel表格内容来修改图片的名称 我本来打
  • MySQL 为什么在实际开发中一般不使用外键约束

    阿里开发手册 强制 不得使用外键与级联 一切外键概念必须在应用层解决 1 外键优点 保证数据的完整性和一致性 级联操作方便 将数据完整性判断托付给了数据库完成 减少了程序的代码量 2 外键缺点 业务数据生成顺序 未必一定可以先生成外键的值
  • 树莓派街机乱码--batocera 中文乱码 --RetroArch 中文乱码

    1 下载中文字体1 重命名为NanumMyeongjo ttf 2 打开WinSCP 连接树莓派 用户名密码为 root linux 3 替换 usr share fonts truetype nanum目录下的NanumMyeongjo
  • OIer JCY

    OIer JCY 一 初一的寒假 大雪纷飞 JCY来到了他的初中 那是坐落在长春市边缘的一栋L形的建筑 冗长的走廊两边设着教室 教室和走廊之间只有门上和靠天花板的地方开着小玻璃窗 透进来些许微弱的光线 灯又不常开着 因而整个走廊总是十分昏暗
  • k8s里面Deploy控制器的使用

    为了更好的解决服务编排的问题 kubernetes在V1 2版本开始 引入了Deployment控制器 值得一提的是 这种控制器并不直接管理pod 而是通过管理ReplicaSet来简介管理Pod 即 Deployment管理Replica
  • 剑指Offer第六十一题:序列化二叉树

    题目描述 请实现两个函数 分别用来序列化和反序列化二叉树 思路 这里序列化就是直接先序遍历即可 但是反序列化指输入序列 返回tree 这里由于左右子树位置不知道 所以在序列化的时候加入 字符 以此判断子树为空 注 这里需要使用char 转s
  • 通用Mapper插件和MyBatis拦截器的使用

    通用Mapper和MyBatis拦截器的使用 MyBatis拦截器 拦截器的使用 MyBatis 拦截器的简单实现 实例结果验证 orderBy createTime默认排序 拦截器在项目中的使用 通用Mapper 简介 使用教程 通用Ma
  • 子词切分算法

    最近使用transformer训练机器翻译模型 期间也看了一些关于数据预处理分词的方法 了解了transformer 1 的subtokenizer以及bpe算法 其中subtokenizer分为形成词汇表与处理训练文本两个部分 形成词汇表
  • 呼叫中心中间件(mod_cti基于FreeSWITCH)-排队(ACD 话务分配)接口

    进入排队 cti acd acdname maxwaittime s priority
  • I - Ultimate Army(栈)

    I Ultimate Armyhttps vjudge csgrandeur cn problem Gym 102267I include
  • Xcode工程依赖

    我使用的Xcode版本 3 2 6 通过Xcode设置工程依赖之后 Xcode会先编译被依赖工程 最后编译有依赖工程 达到控制编译顺序的目的 但是设置依赖这种办法 只适用于所有的工程拥有相同的配置 Debug与Release 这种情况下 如
  • Linux 命令 ps aux 命令解析

    一 简介 PS 是 Linux 系统命令之一 在 Linux 中是查看进程的命令 查看正处于 Running 的进程 linux 上进程有 5 种状态 运行 正在运行或在运行队列中等待 中断 休眠中 受阻 在等待某个条件的形成或接收到信号
  • 菜鸟学四轴控制器之6:刀具半径补偿算法

    为什么要有刀具补偿 想象一下 如果我们的刀具可以理想到半径无穷小 倒是不需要考虑半径的补偿 但是实际上我们用到的是刀具的边沿在雕刻物体 如下图 简单来看 好像是直接平行于轮廓进行移动就可以了 其实不然 单条直线的雕刻是平行 但是直线和直线
  • /etc/rc.d/rc.sysinit脚本分析

    bin bash etc rc d rc sysinit run once at boot time Rerun ourselves through initlog 通过 sbin initlog 命令重新运行自己 if z IN INIT
  • 【Jenkins】安装提示: this account either does not have the privilege logon as a service

    错误详情 安装 Jenkins 时系统提示如下错误 this account either does not have the privilege logon as a service 1 解决方案 2 选择 本地安全策略 按下Win R组
  • C++11之用户自定义字面量(ClassType operator““_C(param...))

    系列文章 C 11之正则表达式 regex match regex search regex replace C 11之线程库 Thread Mutex atomic lock guard 同步 C 11之智能指针 unique ptr s
  • QT开发错误集

    1 error multiple definition of QWidget 在项目 pro中 SOURCES 处添加的 h和 cpp文件有重复添加 将重复的去掉就可以了 2 VS2010 QT 很多代码下面会出现红色波浪线 项目 属性 v
  • Python员工信息作业

    作业简介 根据用户输入 来实现增删改查 处理员工信息数据 1 信息格式 2 文本数据 1 Alex Li 22 13651054608 IT 2013 04 01 2 Jack Wang 28 13451024608 HR 2015 01