python员工信息管理_Python函数案例——员工信息管理
发布日期:2021-10-31 18:34:47 浏览次数:53 分类:技术文章

本文共 16585 字,大约阅读时间需要 55 分钟。

员工信息管理

简单的员工信息增删改查程序

表信息

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

增加

add staff_table Alex Li,25,134435344,IT,2015-10-29

以phone做唯一键(即不允许表里有手机号重复的情况),staff_id需自增

查询支持三种语法

find name,age from staff_table where age > 22

find * from staff_table where dept = "IT"

find * from staff_table where enroll_date like ""

删除指定员工信息纪录

del from staff_table where dept = "IT"

更新记录

update staff_table set dept="Market" where dept = "IT"

update staff_table set age=25 where name = "Alex Li"

流程图

语法分析

def syntax_parser(input_sql):

"""

解析sql语句并执行

:param input_sql:

:return:

"""

# print_log("syntax_parser sql star")

syntax_list ={

'find': syntax_find,

'del': syntax_del,

'add': syntax_add,

'update': syntax_update

}

if input_sql.split()[0] in syntax_list.keys() and 'staff_table' in input_str.split():

if 'where' in input_sql.split():

query_clause, where_clause = input_sql.split("where")

# print_log(query_clause + where_clause)

# 执行where条件

match_data = syntax_where(where_clause.strip())

input_action = query_clause.split()[0]

# 执行不同的action

syntax_list[input_action](match_data, query_clause)

else:

match_data = []

for ind, val in enumerate(STAFF_INFO["id"]):

row = []

for col in COLUMN_NAME:

row.append(STAFF_INFO[col][ind])

match_data.append(row)

syntax_list[input_sql.split()[0]](match_data, input_sql.strip())

else:

print_log("语法错误,find/del/add/updata name,age from [staff_table] [where] age [,=,like][1]", 'error')

where语句分析

def syntax_where(where_clause):

"""

解析where条件

where age > 22

:param where_clause:

:return:

"""

# 操作字符

op_list = [">", "

for op_key in op_list:

if op_key in where_clause:

q_name, q_cond = where_clause.split(op_key)

if q_name.strip() in COLUMN_NAME and q_cond.strip() != "":

match_data = op_compare(q_name.strip(), q_cond.strip(),op_key)

return match_data

else:

if not q_name.strip() in COLUMN_NAME:

error_str = "语法错误,字段%s不存在" % q_name

else:

error_str = "条件值为空"

print_log(error_str, "error")

return False

else:

print_log("语法错误,符号不在[,=,like]中","error")

return False

where 语句的比较运算

def convert_str(f_val, f_cond, f_compare_str):

"""

字符串拼接成条件

:param f_cond:

:param f_val:

:return:

"""

if f_cond.find("'") != -1:

val = "'" + f_val + "'"

elif f_cond.find("\"") != -1:

val = "\"" + f_val + "\""

else:

val = "'" + f_val + "'"

f_cond = "'" + f_cond + "'"

if f_compare_str == 'in':

# 字符比较"'2015' in '2016-02-01'"

exp_str = "%s%s%s" % (val, f_compare_str, f_cond)

else:

# 字符比较

exp_str = "%s%s%s" % (f_cond, f_compare_str, val)

return exp_str

def op_compare(q_name, q_cond, compare_str):

"""

解析where 语句的操作符

:param q_name:

:param q_cond:

:param compare_str:

:return:

"""

match_data = []

if compare_str == "=":

compare_str = "=="

for ind, val in enumerate(STAFF_INFO[q_name]):

if compare_str != "like" and q_cond.isdigit():

# 数字比较

exp_str = "%d%s%d" % (int(val), compare_str, int(q_cond))

elif compare_str != "like" and not q_cond.isdigit():

# 转换操作符两边字符串

# 把val两边加上'val'或"val" ,与输入字符串比较 'Sales' = 'Sales' or "Sales" = "Sales"

# 字符比较

exp_str = convert_str(val, q_cond, compare_str)

# print_log(exp_str)

else:

# if compare_str = like then compare_str = ' in '

op_str = ' in '

# 字符比较

exp_str = convert_str(val, q_cond, op_str)

# print_log(exp_str)

if eval(exp_str):

row_data = []

for col in COLUMN_NAME:

row_data.append(STAFF_INFO[col][ind])

match_data.append(row_data)

# print(tabulate(match_data, headers=COLUMN_NAME, tablefmt="grid"))

return match_data

解析删除语句

def syntax_del(dataset, query_clause):

"""

解析删除语句

del from staff_table where id=3

:param dataset:

:param query_clause:

:return:

"""

for row in dataset:

staff_id = row[0] # 得到id值

staff_index = STAFF_INFO['id'].index(staff_id) # 得到id值在STAFF_INFO[id]的索引

# print_log(staff_index)

for col in COLUMN_NAME:

STAFF_INFO[col].remove(STAFF_INFO[col][staff_index]) # 修改col_name值

save_db()

print_log("成功删除%s条纪录" % len(dataset))

解析增加语句

def syntax_add(dataset, query_clause):

"""

解析增加语句

add staff_table Alex Li,25,134435344,IT,2015-10-29

:param dataset: dataset = [[1,Alex Li,18,13651054608,开发,2013-04-01]]

:param query_clause:

:return:

"""

# 得到增加的值列表

add_data = [col.strip() for col in query_clause.split("staff_table")[-1].split(',')]

phone_ind = COLUMN_NAME.index("phone") # 得到手机所在列

if len(COLUMN_NAME) - 1 == len(add_data):

# 得到最后一行数据,自增长最后一行数据Id最大

max_id = dataset[-1][0]

# 自增长ID

max_id = int(max_id) + 1

# 把ID插入到第一列

add_data.insert(0,str(max_id))

# 得到手机号

phone_val = add_data[phone_ind]

# 判断手机号是否重复

if not (phone_val in STAFF_INFO["phone"]):

# 把数据插入到STAFF_INFO

for index, col in enumerate(COLUMN_NAME):

STAFF_INFO[col].append(add_data[index])

print(tabulate(STAFF_INFO, headers=COLUMN_NAME))

save_db()

print_log("成功添加1条纪录到staff_table表")

else:

print_log("手机号%s重复" %phone_val ,'error')

else:

print_log("语法错误,列数不对,必须字段%s:"% COLUMN_NAME[1:], "error")

解析修改语句

def syntax_update(dataset, query_clause):

"""

修改语句 update staff_table set age=25 where name='Alex Li'

:param dataset:

:param query_clause:

:return:

"""

if "set" in query_clause:

formula_str = query_clause.split("set")

col_name, new_val = formula_str[-1].strip().split('=')

# print(col_name, new_val)

# STAFF_INFO[col_name]

if new_val.find("'") == 0:

new_val = new_val.replace("'", "")

elif new_val.find("\"") == 0:

new_val = new_val.replace("\"", "")

for row in dataset:

staff_id = row[0] # 得到id值

staff_index = STAFF_INFO['id'].index(staff_id) # 得到id值在STAFF_INFO[id]的索引

STAFF_INFO[col_name][staff_index] = new_val # 修改col_name值

# print_log(STAFF_INFO)

save_db()

print_log("成功修改了%s条数据!" % len(dataset))

else:

print_log("语法错误,未检测到set", "error")

保存数据

def save_db():

"""

#把修改的数据保存到硬盘上

:return:

"""

f = open("%s.new"%DB_FILE, "w",encoding="utf-8")

# for k in COLUMN_NAME:

# row = []

# row = STAFF_INFO[k]

for ind, val in enumerate(STAFF_INFO["id"]):

row = []

for col in COLUMN_NAME:

row.append(STAFF_INFO[col][ind])

w_data = ",".join(row)

# print_log(w_data)

f.write(w_data+"\n")

f.close()

os.remove(DB_FILE)

os.rename("%s.new"%DB_FILE, DB_FILE) # 回写原来的文件

解析查询语句

def syntax_find(dataset, query_clause):

"""

查询语句解析

:param dataset:

:param query_clause:

:return:

"""

query_col = query_clause.split("from")[0][4:].split(',') # 得到name,age

filter_col = [col.strip() for col in query_col] # 去除col中的空格

# print(query_col)

reformat_dataset = []

if '*' in filter_col: # 输出所有列

print(tabulate(dataset, headers=COLUMN_NAME, tablefmt="grid"))

print_log("匹配到%s条数据!" % len(dataset))

else:

for row in dataset: # 筛选列

filter_val = []

for col in filter_col:

index = COLUMN_NAME.index(col)

filter_val.append(row[index])

reformat_dataset.append(filter_val)

print(tabulate(reformat_dataset, headers=COLUMN_NAME, tablefmt="grid"))

print_log("匹配到%s条数据!" % len(reformat_dataset))

主函数

if __name__ == '__main__':

"""

用户信息查询

"""

# 把数据载入内存

STAFF_INFO = load_db()

while True:

input_str = input("[staff db:]").strip()

if not input_str : continue

syntax_parser(input_str)

详细代码

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# @Time : 2018/3/17 12:27

# @Site :

# @File : staff_info_manage.py

# @Software: PyCharm

"""

简单的员工信息增删改查程序

表信息

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

增加

add staff_table Alex Li,25,134435344,IT,2015-10-29

以phone做唯一键(即不允许表里有手机号重复的情况),staff_id需自增

查询支持三种语法

find name,age from staff_table where age > 22

find * from staff_table where dept = "IT"

find * from staff_table where enroll_date like "2013"

删除指定员工信息纪录

del from staff_table where dept = "IT"

更新记录

update staff_table set dept="Market" where dept = "IT"

update staff_table set age=25 where name = "Alex Li"

"""

from tabulate import tabulate

import os

# 存储信息的文件

DB_FILE = "staff.db"

COLUMN_NAME = ['id', 'name', 'age', 'phone', 'dept', 'enroll_date']

# 打印信息

def print_log(msg, log_type="info"):

if log_type == 'info':

print("\033[32;1m%s\033[0m" %msg)

elif log_type == 'error':

print("\033[31;1m%s\033[0m" %msg)

def load_db():

"""

载入员工信息

:return:

"""

staff_data = {}

# 构建字典空列表

#{'id': [],'name':[],'age': [],'phone':[],'dept':[],'enrolled_date'[]

for d in COLUMN_NAME:

staff_data[d] = []

with open(DB_FILE, 'r', encoding='utf-8') as f:

for line in f:

staff_datas = line.split(",")

# 构建员工信息字典

for ind, d in enumerate(staff_datas):

staff_data[COLUMN_NAME[ind]].append(d.strip()) # 去掉末尾回车

return staff_data

def convert_str(f_val, f_cond, f_compare_str):

"""

字符串拼接成条件

:param f_cond:

:param f_val:

:return:

"""

if f_cond.find("'") != -1:

val = "'" + f_val + "'"

elif f_cond.find("\"") != -1:

val = "\"" + f_val + "\""

else:

val = "'" + f_val + "'"

f_cond = "'" + f_cond + "'"

if f_compare_str == 'in':

# 字符比较"'2015' in '2016-02-01'"

exp_str = "%s%s%s" % (val, f_compare_str, f_cond)

else:

# 字符比较

exp_str = "%s%s%s" % (f_cond, f_compare_str, val)

return exp_str

def op_compare(q_name, q_cond, compare_str):

"""

解析where 语句的操作符

:param q_name:

:param q_cond:

:param compare_str:

:return:

"""

match_data = []

if compare_str == "=":

compare_str = "=="

for ind, val in enumerate(STAFF_INFO[q_name]):

if compare_str != "like" and q_cond.isdigit():

# 数字比较

exp_str = "%d%s%d" % (int(val), compare_str, int(q_cond))

elif compare_str != "like" and not q_cond.isdigit():

# 转换操作符两边字符串

# 把val两边加上'val'或"val" ,与输入字符串比较 'Sales' = 'Sales' or "Sales" = "Sales"

# 字符比较

exp_str = convert_str(val, q_cond, compare_str)

# print_log(exp_str)

else:

# if compare_str = like then compare_str = ' in '

op_str = ' in '

# 字符比较

exp_str = convert_str(val, q_cond, op_str)

# print_log(exp_str)

if eval(exp_str):

row_data = []

for col in COLUMN_NAME:

row_data.append(STAFF_INFO[col][ind])

match_data.append(row_data)

# print(tabulate(match_data, headers=COLUMN_NAME, tablefmt="grid"))

return match_data

def syntax_where(where_clause):

"""

解析where条件

where age > 22

:param where_clause:

:return:

"""

# 操作字符

op_list = [">", "

for op_key in op_list:

if op_key in where_clause:

q_name, q_cond = where_clause.split(op_key)

if q_name.strip() in COLUMN_NAME and q_cond.strip() != "":

match_data = op_compare(q_name.strip(), q_cond.strip(),op_key)

return match_data

else:

if not q_name.strip() in COLUMN_NAME:

error_str = "语法错误,字段%s不存在" % q_name

else:

error_str = "条件值为空"

# print_log(error_str, "error")

return False

else:

print_log("语法错误,符号不在[,=,like]中","error")

return False

def syntax_del(dataset, query_clause):

"""

解析删除语句

del from staff_table where id=3

:param dataset:

:param query_clause:

:return:

"""

for row in dataset:

staff_id = row[0] # 得到id值

staff_index = STAFF_INFO['id'].index(staff_id) # 得到id值在STAFF_INFO[id]的索引

# print_log(staff_index)

for col in COLUMN_NAME:

STAFF_INFO[col].remove(STAFF_INFO[col][staff_index]) # 修改col_name值

save_db()

print_log("成功删除%s条纪录" % len(dataset))

def syntax_add(dataset, query_clause):

"""

解析增加语句

add staff_table Alex Li,25,134435344,IT,2015-10-29

:param dataset: dataset = [[1,Alex Li,18,13651054608,开发,2013-04-01]]

:param query_clause:

:return:

"""

# 得到增加的值列表

add_data = [col.strip() for col in query_clause.split("staff_table")[-1].split(',')]

phone_ind = COLUMN_NAME.index("phone") # 得到手机所在列

if len(COLUMN_NAME) - 1 == len(add_data):

# 得到最后一行数据,自增长最后一行数据Id最大

max_id = dataset[-1][0]

# 自增长ID

max_id = int(max_id) + 1

# 把ID插入到第一列

add_data.insert(0,str(max_id))

# 得到手机号

phone_val = add_data[phone_ind]

# 判断手机号是否重复

if not (phone_val in STAFF_INFO["phone"]):

# 把数据插入到STAFF_INFO

for index, col in enumerate(COLUMN_NAME):

STAFF_INFO[col].append(add_data[index])

print(tabulate(STAFF_INFO, headers=COLUMN_NAME))

save_db()

print_log("成功添加1条纪录到staff_table表")

else:

print_log("手机号%s重复" %phone_val ,'error')

else:

print_log("语法错误,列数不对,必须字段%s:"% COLUMN_NAME[1:], "error")

def syntax_update(dataset, query_clause):

"""

修改语句 update staff_table set age=25 where name='Alex Li'

:param dataset:

:param query_clause:

:return:

"""

if "set" in query_clause:

formula_str = query_clause.split("set")

col_name, new_val = formula_str[-1].strip().split('=')

# print(col_name, new_val)

# STAFF_INFO[col_name]

if new_val.find("'") == 0:

new_val = new_val.replace("'", "")

elif new_val.find("\"") == 0:

new_val = new_val.replace("\"", "")

for row in dataset:

staff_id = row[0] # 得到id值

staff_index = STAFF_INFO['id'].index(staff_id) # 得到id值在STAFF_INFO[id]的索引

print(STAFF_INFO[col_name][staff_index])

STAFF_INFO[col_name][staff_index] = new_val # 修改col_name值

# print_log(STAFF_INFO)

save_db()

print_log("成功修改了%s条数据!" % len(dataset))

else:

print_log("语法错误,未检测到set", "error")

def save_db():

"""

#把修改的数据保存到硬盘上

:return:

"""

f = open("%s.new"%DB_FILE, "w",encoding="utf-8")

# for k in COLUMN_NAME:

# row = []

# row = STAFF_INFO[k]

for ind, val in enumerate(STAFF_INFO["id"]):

row = []

for col in COLUMN_NAME:

row.append(STAFF_INFO[col][ind])

w_data = ",".join(row)

# print_log(w_data)

f.write(w_data+"\n")

f.close()

os.remove(DB_FILE)

os.rename("%s.new"%DB_FILE, DB_FILE) # 回写原来的文件

def syntax_parser(input_sql):

"""

解析sql语句并执行

:param input_sql:

:return:

"""

# print_log("syntax_parser sql star")

syntax_list ={

'find': syntax_find,

'del': syntax_del,

'add': syntax_add,

'update': syntax_update

}

if input_sql.split()[0] in syntax_list.keys() and 'staff_table' in input_str.split():

if 'where' in input_sql.split():

query_clause, where_clause = input_sql.split("where")

# print_log(query_clause + where_clause)

# 执行where条件

match_data = syntax_where(where_clause.strip())

input_action = query_clause.split()[0]

# 执行不同的action

syntax_list[input_action](match_data, query_clause)

else:

match_data = []

for ind, val in enumerate(STAFF_INFO["id"]):

row = []

for col in COLUMN_NAME:

row.append(STAFF_INFO[col][ind])

match_data.append(row)

syntax_list[input_sql.split()[0]](match_data, input_sql.strip())

else:

print_log("语法错误,find/del/add/update name,age from [staff_table] [where] age [,=,like][1]", 'error')

def syntax_find(dataset, query_clause):

"""

查询语句解析

:param dataset:

:param query_clause:

:return:

"""

query_col = query_clause.split("from")[0][4:].split(',') # 得到name,age

filter_col = [col.strip() for col in query_col] # 去除col中的空格

# print(query_col)

reformat_dataset = []

if '*' in filter_col: # 输出所有列

print(tabulate(dataset, headers=COLUMN_NAME, tablefmt="grid"))

print_log("匹配到%s条数据!" % len(dataset))

else:

for row in dataset: # 筛选列

filter_val = []

for col in filter_col:

index = COLUMN_NAME.index(col)

filter_val.append(row[index])

reformat_dataset.append(filter_val)

print(tabulate(reformat_dataset, headers=COLUMN_NAME, tablefmt="grid"))

print_log("匹配到%s条数据!" % len(reformat_dataset))

if __name__ == '__main__':

"""

用户信息查询

"""

# 把数据载入内存

STAFF_INFO = load_db()

while True:

input_str = input("[staff db:]").strip()

if not input_str : continue

syntax_parser(input_str)

详细代码

python函数小案例

python函数 目录 python函数 1.写一个函数求三个数的和,并返回结果 2.写一个函数,求平均值,并返回结果 写一个函数,求每个数与平均值之间的差,并放回结果 1.写一个函数求三个数的和,并 ...

Day03 - Python 函数

1. 函数简介 函数是组织好的,可重复使用的,用来实现单一或相关联功能的代码段. 函数能提高应用的模块性,和代码的重复利用率.Python提供了许多内建函数,比如print():也可以自己创建函数,这 ...

Python入门(案例)

Python入门(案例) #一.上课案例: #输出hello wordprint('hello word') #python注释有两种#1.单行注释#这是单行注释#2.多行注释'''这是多行注释''' ...

Python 函数定义和使用

# 函数的概念 # 概念 # 写了一段代码实现了某个小功能; 然后把这些代码集中到一块, 起一个名字; 下一次就可以根据这个名字再次使用这个代码块, 这就是函数 # 作用 # 方便代码的重用 # 分解 ...

Python函数中参数类型

在学习Python函数的时候,函数本身的定义和调用并不是很复杂,但是函数的参数类型和用法的确有些复杂.在此做一个小结,加深理解. Python参数的定义 负责给函数提供一些必要的数据或信息,以保证函数 ...

python函数闭包-装饰器-03

可调用对象 callable()  # 可调用的(这个东西加括号可以执行特定的功能,类和函数) 可调用对象即  callable(对象)  返回为  True  的对象 x = 1 print(cal ...

Python 函数返回值、作用域

函数返回值 多条return语句: def guess(x): if x > 3: return "> 3" else: return "<= 3&qu ...

python 函数、参数及参数解构

函数 数学定义 y=f(x), y是x函数,x是自变量.y=f(x0,x1...xn) Python函数 由若干语句组成的语句块,函数名称,参数列表构成,它是组织代码的最小单位 完成一定的功能 函数作 ...

Python函数07&sol;有参装饰器&sol;多个装饰器装饰一个函数

Python函数07/有参装饰器/多个装饰器装饰一个函数 目录 Python函数07/有参装饰器/多个装饰器装饰一个函数 内容大纲 1.有参装饰器 2.多个装饰器装饰一个函数 3.今日总结 3.今日练 ...

随机推荐

Thread&period;Sleep引发ThreadAbortException异常

短信平台记录日志模块,是通过异步方式来记录的,即日志工具类里初始化一个Queue对象,公共的写日志方法的处理逻辑是把日志消息放到Queue里.构造器里设定一个死循环,不停的读队,然后把日志消息持久化到 ...

mysql 用户方面的操作

1.只新建用户的操作 mysql -u root -p密码mysql> insert into mysql.user(Host,User,Password) values(‘localhost’ ...

IntelliJ IDEA&plus;Tomcat&plus;Nginx运行git项目

1.克隆Git项目到本地 (1)设置Git工具路径:file>settings>Version Control>Git (2)设置GitHub账户:file>settings& ...

使用VsCode编写和调试&period;NET Core项目

​ 本来我还想介绍以下VSCode或者donet core,但是发现都是废话,没有必要,大家如果对这个不了解可以直接google这两个关键字,或者也根本不会看我这边文章. ​ 好直接进入主题了,本文的 ...

jquery带参插件函数的编写

Linux 常用基本指令

1.ls 参数: -a:列出所有目录(“.”开头的是隐藏文件) -l: 以长格式列出目录下的内容列表 2.cd cd  切换到家目录 cd ~ 切换到家目录 cd .. 切换到上一级目录 3.pwd ...

Centos7服务器中通过编译源码安装MySQL

基于在Centos7服务器上使用 yum 安装MySQL5.7到默认路径 在修改文件存储位置的时候,折腾了一番没有将成功将datadir修改为我想要的位置 我决定再尝试一下通过编译源码来自定义安装: ...

和我一起打造个简单搜索之IK分词以及拼音分词

elasticsearch 官方默认的分词插件,对中文分词效果不理想,它是把中文词语分成了一个一个的汉字.所以我们引入 es 插件 es-ik.同时为了提升用户体验,引入 es-pinyin 插件.本 ...

python 历险记(二)— python 的面向对象

目录 前言 类和对象 如何定义和实例化类? 如何定义和使用属性? 什么是方法? 静态方法和普通方法 构造函数该怎么写? str 方法怎么写? 多态是什么? 继承性和 java 是一样的吗? 父类和子类 ...

转载地址:https://blog.csdn.net/weixin_40006779/article/details/110628612 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:excel行转列_做了7年Excel数据分析,给你几点建议,让你效率翻倍
下一篇:fastjson list转json字符串_Java几种常用JSON库性能比较

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月05日 20时41分05秒