热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Python学习day4作业

Python学习day4作业@(学习)[python]Python学习day4作业day4作业员工信息表程序说明基本流程图程序代码程序测试day4作业:员工信息表作业需求1.

Python学习day4作业

@(学习)[python]

  • Python学习day4作业
    • day4作业员工信息表
    • 程序说明
    • 基本流程图
    • 程序代码
    • 程序测试

day4作业:员工信息表

作业需求
1.模糊查询,查询结果可显示条数,支持例如以下语法:
select name,age from staff_table where age > 22
select * from staff_table where dept = “IT”
select * from staff_table where enroll_date like “2013”
2.可创建新员工纪录,以phone做唯一键,staff_id需自增;
3.可删除指定员工信息纪录,输入员工id,即可删除;
4.可修改员工信息,语法如下:
update staff_table set dept = "Market" where dept = "IT";
5.充分使用函数,请尽你的最大限度来减少重复代码;

  • [x] 博客
  • [x] 模糊查询
  • [x] 创建员工纪录
  • [x] 删除员工纪录
  • [x] 修改员工纪录

ygqygq2的博客地址

1.程序说明

实现功能如下

  • [x] 博客
  • [x] 模糊查询
  • [x] 创建员工纪录
  • [x] 删除员工纪录
  • [x] 修改员工纪录

2.基本流程图

这里写图片描述

3.程序代码

#!/usr/bin/env python
# _*_coding:utf-8_*_
'''
* Created on 2016/12/5 22:31.
* @author: Chinge_Yang.
'''


import os
import sys


def file_to_data(table):
"""
# 读文件成数据
:param
:return:
"""

n = 0
data_list = []
with open(table, "r", encoding="utf-8") as f:
for line in f:
line = line.strip() # 去除换行符
if n == 0:
# ["staff_id","name","age","phone","dept","enroll_date"]
struct_list = line.split(",") # 第一行
else:
line_list = line.split(",")
data_list.append(line_list) # 其它行
n += 1
return struct_list, data_list


def data_to_file(struct_list, data_list, table):
"""
# 把数据写入文件
:return:
"""

with open(table, "w", encoding="utf-8") as f:
f.write(','.join(struct_list) + "\n")
for sub_list in data_list:
f.write(",".join(sub_list) + "\n")
print("Done!")


def print_help(action):
print("The grammar of the {} support likes:\n".format(action))
if action == "select":
print("\tselect * from staff_table;")
print("\tselect name,age from staff_table where age > 22;")
print("\tselect * from staff_table where dept = \"IT\";")
print("\tselect * from staff_table where enroll_date like \"2013\";")
elif action == "add":
print("\tadd [Alex Li,22,13651054608,IT,2013-04-01];")
elif action == "update":
print("\tupdate staff_table set dept = \"Market\" where dept = \"IT\";")
elif action == "delete":
print("\tdelete 5;")


def get_column_number(column, struct_list):
"""
# 获取列位置
:param column: 列名,此处只实现支持一个
:return:
"""

column_number = struct_list.index(column) # 结果为数字
return column_number


def input_sql():
# 获取输入SQL
exit_flag = False
while exit_flag is not True:
print("-".center(60, "-"))
print("Tip: Input 【help [select/update/add/delete]】 to get help.")
print("-".center(60, "-"))
sql = input("Please input SQL:").strip().strip(";")
if sql.startswith('help'):
action = sql.split(" ")[1]
print_help(action)
continue
if sql == "q" or sql == "quit":
exit(" Bye Bye ".center(60, "#"))
exit_flag = True
return sql


def sql_to_list(sql):
tmp_sql = sql.split(' ')
sql_list = []
tmp = ''
flag = 1 # 列表添加元素标识
for l in tmp_sql:
if l.startswith('"') and l.endswith('"'):
flag = 1
elif l.startswith('"') and (not l.endswith('"')):
flag = 0
tmp = l + ' '
elif (not l.startswith('"')) and (not l.endswith('"')):
if flag == 0:
l += ' '
tmp += l
else:
flag = 1
elif (not l.startswith('"')) and l.endswith('"'):
if flag == 0:
tmp += l
flag = 1
sql_list.append(tmp)
continue

if flag == 1:
sql_list.append(l)
return sql_list


def check_table(table, c_table):
"""
# 判断表是否存在
:param table: 表名
:return:
"""

if table != c_table:
print("Your input table \033[31m{}\033[0m is not exists,"
"please check!".format(c_table))
print("#".center(60, "#"))
return True # 标记给continue_flag


def check_quotes(str):
"""
:param str: 需要处理的字符串
:return: 返回无符号的字符串
"""

if '"' in str:
str = str.strip('"')
return str


def auto_increment_id(data_list):
file = "auto_increment_id"
max_staff_id = int(data_list[-1][0]) # 表中最大的staff_id
id = 0 # 初始化
if os.path.exists(file): # 自增id文件存在时
with open(file, "r+") as f:
for line in f:
id = int(line)
if max_staff_id <= id:
new_staff_id = id + 1
else:
new_staff_id = max_staff_id + 1
with open(file, "w+") as f:
f.write(str(new_staff_id))
return new_staff_id


def analyze(sql):
input_info = sql_to_list(sql)
# return input_info
action = input_info[0] # 查:select;增:add;改:update;删:delete
return action


def select(sql, struct_list, data_list, table): # select sql语法分析
input_info = sql_to_list(sql)
select_column = input_info[1].split(",") # 可能有“,”号
try:
table_name = input_info[3]
except Exception as e:
print("Your input is error!")
return True
continue_flag = check_table(table, table_name)
if continue_flag is True:
return True

all_column = False
all_line = False
# 查询列,* 或者指定列
if "*" in select_column: # 打印所有列
all_column = True
else:
column_numbers = [] # 输出列的数字列表
for s_column in select_column:
s_number = get_column_number(s_column, struct_list)
column_numbers.append(s_number)

if "where" in sql:
# 由于双引号问题,此处加上双引号
where_flag = input_info[4] # where
condition_column = input_info[5] # 条件字段
condition_str = input_info[6] # 限制条件关键字,支持“=”,“>=”,“like”等
condition_value = input_info[7] # 条件参数
condition_value = check_quotes(condition_value) # 去除双引号
column_number = get_column_number(condition_column, struct_list) # 列位置

match_data_list = [] # 匹配出来的结果,列表格式,
# 查询行,有like、>=、= 等
if where_flag == "where": # 有where
if condition_str == "like":
# like
for line in data_list: # line也是列表
if condition_value in line[column_number]: # 匹配like
match_data_list.append(line)
elif condition_str == "=":
for line in data_list:
if line[column_number] == condition_value:
match_data_list.append(line)
elif condition_str == ">":
for line in data_list:
if line[column_number] > condition_value:
match_data_list.append(line)
elif condition_str == ">=":
for line in data_list:
if line[column_number] >= condition_value:
match_data_list.append(line)
elif condition_str == "<":
for line in data_list:
if line[column_number] match_data_list.append(line)
elif condition_str == "<=":
for line in data_list:
if line[column_number] <= condition_value:
match_data_list.append(line)
else: # 无where,取所有行
all_line = True
match_data_list = data_list

# 打印结果
print("The select result:")
print("#".center(60, "#"))
print("\033[32m{}\033[0m rows in set".format(len(match_data_list)))
if all_column is True:
print("{:>8} {:>8} {:>8} {:>8} {:>8} {:>8}".format(*struct_list))
for line in match_data_list:
print("{:>8} {:>8} {:>8} {:>8} {:>8} {:>8}".format(*line))
else:
len_num = len(select_column)
format_str = '{:>8} ' * len_num
print(format_str.format(*select_column))
for line in match_data_list:
line_list = []
for s in column_numbers:
line_list.append(line[s])
print(format_str.format(*line_list))
print("#".center(60, "#"))

def add(sql, struct_list, data_list, table):
# sql: Alex Li,22,13651054608,IT,2013-04-01
input_info = sql.strip().strip("add [").strip("]")
add_list = input_info.split(",")
phOne= add_list[2]
phone_exist = False
for d_list in data_list:
if phOne== d_list[3]:
phone_exist = True
if phone_exist is True:
print("Thone phone is exist,can't add.")
return True
else:
new_staff_id = auto_increment_id(data_list)
add_list.insert(0, str(new_staff_id))
data_list.append(add_list)
data_to_file(struct_list, data_list, table)


def delete(sql, struct_list, data_list, table):
# delete 5;
delete_flag = False
input_info = sql_to_list(sql)
staff_id = input_info[1]
for d_list in data_list:
if staff_id == d_list[0]:
delete_flag = True
data_list.remove(d_list)

if delete_flag is not True:
print("The staff_id is not exist,can't delete.")
else:
data_to_file(struct_list, data_list, table)


def update(sql, struct_list, data_list, table):
# update staff_table set dept = "Market" where dept = "IT"; 只允许修改age,phone,dept,enroll_date
input_info = sql_to_list(sql)
table_name = input_info[1]
set_flag = input_info[2]
modify_column = input_info[3] # 修改的字段
equal_flag = input_info[4] # 等于符号
modify_value = input_info[5] # 修改后的值
modify_value = check_quotes(modify_value) # 去除双引号
where_flag = input_info[6]
condition_column = input_info[7] # 条件字段
condition_str = input_info[8] # 限制条件关键字,只支持“=”
condition_value = input_info[9] # 条件参数
condition_value = check_quotes(condition_value) # 去除双引号
modify_column_number = get_column_number(modify_column, struct_list) # 列位置
condition_column_number = get_column_number(condition_column, struct_list) # 列位置

modify_flag = False
continue_flag = check_table(table, table_name)
if continue_flag is True:
return True
if set_flag == "set" and equal_flag == "=" and where_flag == "where" and condition_str == "=":
phone_exist = False
phOne= modify_value
for d_list in data_list:
if phOne== d_list[3]:
phone_exist = True
if phone_exist is True:
print("Thone phone is exist,can't update.")
return True
for d_list in data_list:
# 由于双引号问题,此处加上双引号
if d_list[condition_column_number] == condition_value:
d_list[modify_column_number] = modify_value
modify_flag = True
if modify_flag is not True:
print("Not match any record!")
else:
data_to_file(struct_list, data_list, table)
else:
print("Your input is error!")


def main():
exit_flag = False
table = "staff_table"
while exit_flag is not True:
sql = input_sql()
action = analyze(sql)
struct_list, data_list = file_to_data(table)
if action == "select":
continue_flag = select(sql, struct_list, data_list, table)
if continue_flag is True:
continue # 重新循环
elif action == "add":
continue_flag = add(sql, struct_list, data_list, table)
if continue_flag is True:
continue # 重新循环
elif action == "update":
continue_flag = update(sql, struct_list, data_list, table)
if continue_flag is True:
continue
elif action == "delete":
delete(sql, struct_list, data_list, table)
else:
print("Your input error!")


if __name__ == '__main__':
main()

4.程序测试

cat staff_table

staff_id,name,age,phone,dept,enroll_date
1,Alex Li,22,13651054608,IT,2013-04-01
2,Jim,25,13651058808,IT,2011-09-01
3,Tom,29,13761054698,IT,2010-03-01
4,Suzen,40,13957057707,Manager,2003-01-01
5,Mark,32,13351959999,CTO,2014-08-08

python staff_table_manager.py

------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:help select
The grammar of the select support likes:

select * from staff_table;

select name,age from staff_table where age > 22;
select * from staff_table where dept = "IT";
select * from staff_table where enroll_date like "2013";
------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:select * from staff_table;

The select result:
############################################################
5 rows in set
staff_id name age phone dept enroll_date
1 Alex Li 22 13651054608 IT 2013-04-01
2 Jim 25 13651058808 IT 2011-09-01
3 Tom 29 13761054698 IT 2010-03-01
4 Suzen 40 13957057707 Manager 2003-01-01
5 Mark 32 13351959999 CTO 2014-08-08
############################################################
------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:select name,age from staff_table where age > 22;

The select result:
############################################################
4 rows in set
name age
Jim 25
Tom 29
Suzen 40
Mark 32
############################################################
------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:select * from staff_table where dept = "IT";

The select result:
############################################################
3 rows in set
staff_id name age phone dept enroll_date
1 Alex Li 22 13651054608 IT 2013-04-01
2 Jim 25 13651058808 IT 2011-09-01
3 Tom 29 13761054698 IT 2010-03-01
############################################################
------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:select * from staff_table where enroll_date like "2013";

The select result:
############################################################
1 rows in set
staff_id name age phone dept enroll_date
1 Alex Li 22 13651054608 IT 2013-04-01
############################################################
------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:help update
The grammar of the update support likes:

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

------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:update staff_table set dept = "Market" where dept = "IT";

Done!
------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:select * from staff_table;

The select result:
############################################################
5 rows in set
staff_id name age phone dept enroll_date
1 Alex Li 22 13651054608 Market 2013-04-01
2 Jim 25 13651058808 Market 2011-09-01
3 Tom 29 13761054698 Market 2010-03-01
4 Suzen 40 13957057707 Manager 2003-01-01
5 Mark 32 13351959999 CTO 2014-08-08
############################################################
------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:update staff_table set phOne= 13651054608 where name = "Mark";

Thone phone is exist,can't update.
------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:help add
The grammar of the add support likes:

add [Alex Li,22,13651054608,IT,2013-04-01];

------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:add [Alex Li,22,13651054608,IT,2013-04-01];

Thone phone is exist,can't add.
------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:add [Alex Li,22,13651054666,IT,2013-04-01];

Done!
------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:select * from staff_table where name = "Alex Li";

The select result:
############################################################
2 rows in set
staff_id name age phone dept enroll_date
1 Alex Li 22 13651054608 Market 2013-04-01
6 Alex Li 22 13651054666 IT 2013-04-01
############################################################
------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:help delete
The grammar of the delete support likes:

delete 5;

------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:delete 6
Done!
------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:delete 5
Done!
------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:select * from staff_table;

The select result:
############################################################
4 rows in set
staff_id name age phone dept enroll_date
1 Alex Li 22 13651054608 Market 2013-04-01
2 Jim 25 13651058808 Market 2011-09-01
3 Tom 29 13761054698 Market 2010-03-01
4 Suzen 40 13957057707 Manager 2003-01-01
############################################################
------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:add [Alex Li,22,13651054666,IT,2013-04-01];

Done!
------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:select * from staff_table;

The select result:
############################################################
5 rows in set
staff_id name age phone dept enroll_date
1 Alex Li 22 13651054608 Market 2013-04-01
2 Jim 25 13651058808 Market 2011-09-01
3 Tom 29 13761054698 Market 2010-03-01
4 Suzen 40 13957057707 Manager 2003-01-01
7 Alex Li 22 13651054666 IT 2013-04-01
############################################################
------------------------------------------------------------
Tip: Input 【help [select/update/add/delete]】 to get help.
------------------------------------------------------------
Please input SQL:quit
######################### Bye Bye ##########################

Process finished with exit code 1

推荐阅读
  • 利用python爬取豆瓣电影Top250的相关信息,包括电影详情链接,图片链接,影片中文名,影片外国名,评分,评价数,概况,导演,主演,年份,地区,类别这12项内容,然后将爬取的信息写入Exce ... [详细]
  • 本文详细介绍了如何使用Python中的smtplib库来发送带有附件的邮件,并提供了完整的代码示例。作者:多测师_王sir,时间:2020年5月20日 17:24,微信:15367499889,公司:上海多测师信息有限公司。 ... [详细]
  • 解决问题:1、批量读取点云las数据2、点云数据读与写出3、csf滤波分类参考:https:github.comsuyunzzzCSF论文题目ÿ ... [详细]
  • Python 序列图分割与可视化编程入门教程
    本文介绍了如何使用 Python 进行序列图的快速分割与可视化。通过一个实际案例,详细展示了从需求分析到代码实现的全过程。具体包括如何读取序列图数据、应用分割算法以及利用可视化库生成直观的图表,帮助非编程背景的用户也能轻松上手。 ... [详细]
  • 本文全面解析了 Python 中字符串处理的常用操作与技巧。首先介绍了如何通过 `s.strip()`, `s.lstrip()` 和 `s.rstrip()` 方法去除字符串中的空格和特殊符号。接着,详细讲解了字符串复制的方法,包括使用 `sStr1 = sStr2` 进行简单的赋值复制。此外,还探讨了字符串连接、分割、替换等高级操作,并提供了丰富的示例代码,帮助读者深入理解和掌握这些实用技巧。 ... [详细]
  • importpymysql#一、直接连接mysql数据库'''coonpymysql.connect(host'192.168.*.*',u ... [详细]
  • 本文介绍如何使用 Python 的 DOM 和 SAX 方法解析 XML 文件,并通过示例展示了如何动态创建数据库表和处理大量数据的实时插入。 ... [详细]
  • javascript分页类支持页码格式
    前端时间因为项目需要,要对一个产品下所有的附属图片进行分页显示,没考虑ajax一张张请求,所以干脆一次性全部把图片out,然 ... [详细]
  • 本文介绍了如何利用 `matplotlib` 库中的 `FuncAnimation` 类将 Python 中的动态图像保存为视频文件。通过详细解释 `FuncAnimation` 类的参数和方法,文章提供了多种实用技巧,帮助用户高效地生成高质量的动态图像视频。此外,还探讨了不同视频编码器的选择及其对输出文件质量的影响,为读者提供了全面的技术指导。 ... [详细]
  • 本文介绍了如何使用Python的Paramiko库批量更新多台服务器的登录密码。通过示例代码展示了具体实现方法,确保了操作的高效性和安全性。Paramiko库提供了强大的SSH2协议支持,使得远程服务器管理变得更加便捷。此外,文章还详细说明了代码的各个部分,帮助读者更好地理解和应用这一技术。 ... [详细]
  • 大类|电阻器_使用Requests、Etree、BeautifulSoup、Pandas和Path库进行数据抓取与处理 | 将指定区域内容保存为HTML和Excel格式
    大类|电阻器_使用Requests、Etree、BeautifulSoup、Pandas和Path库进行数据抓取与处理 | 将指定区域内容保存为HTML和Excel格式 ... [详细]
  • 本文介绍了如何通过 Python 代码实现对字符串的特定反转操作。具体而言,给定一个字符串 s,要求在保持所有非英文字母字符位置不变的情况下,将所有英文字母(无论是小写还是大写)的位置进行反转。最终返回经过处理后的字符串 s。 ... [详细]
  • Python 程序转换为 EXE 文件:详细解析 .py 脚本打包成独立可执行文件的方法与技巧
    在开发了几个简单的爬虫 Python 程序后,我决定将其封装成独立的可执行文件以便于分发和使用。为了实现这一目标,首先需要解决的是如何将 Python 脚本转换为 EXE 文件。在这个过程中,我选择了 Qt 作为 GUI 框架,因为之前对此并不熟悉,希望通过这个项目进一步学习和掌握 Qt 的基本用法。本文将详细介绍从 .py 脚本到 EXE 文件的整个过程,包括所需工具、具体步骤以及常见问题的解决方案。 ... [详细]
  • 本文详细介绍了在 Oracle 数据库中使用 MyBatis 实现增删改查操作的方法。针对查询操作,文章解释了如何通过创建字段映射来处理数据库字段风格与 Java 对象之间的差异,确保查询结果能够正确映射到持久层对象。此外,还探讨了插入、更新和删除操作的具体实现及其最佳实践,帮助开发者高效地管理和操作 Oracle 数据库中的数据。 ... [详细]
  • 本文详细介绍了一种利用 ESP8266 01S 模块构建 Web 服务器的成功实践方案。通过具体的代码示例和详细的步骤说明,帮助读者快速掌握该模块的使用方法。在疫情期间,作者重新审视并研究了这一未被充分利用的模块,最终成功实现了 Web 服务器的功能。本文不仅提供了完整的代码实现,还涵盖了调试过程中遇到的常见问题及其解决方法,为初学者提供了宝贵的参考。 ... [详细]
author-avatar
手机用户2502872401
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有