day26 Pyhton select功能语句实现

一.查询语句功能实现

  select id,name where age > '20'

name_value = {'id':0,'name':1,'age':2,'phone':3,'job':4}
sql = 'select id,name where age > 20'#sql = input('>>>').strip()

def format_sql(sql):
    sql = sql.replace('select', '')  # 'select name , age where age > 20' 替换select为空
    sql = sql.replace(' ', '')       # 'name,agewhereage>20' 去掉空格
    col, con = sql.split('where')    # col = 'name,age',con = 'age>20' 以where切割,得到两个参数
    if '*' in col:
        col_lst = name_value.keys() #'*'代表所有的key值'id,'name','age,phone,'job
    else:
        col_lst = col.split(',')     # col_lst = ['name','age'] 得到name,age
    return col_lst,con               # col_lst = ['name','age']   con = 'age>20'

def read_file():#遍历文件里的内容
    with open('userinfo', encoding='utf-8') as f:
        for line in f:
            line_lst = line.strip().split(',')
            yield line_lst#返回一行内容

def show(con,col_l,symbol,condition):#con = age>20 col_l = ['name' ,symbo为l条件比较符号为>,condition为'int(con_value) < int(line_lst[num])
    con_name, con_value = con.split(symbol)  # con_name = 'age',con_value = 20 以条件比较符号>进行切割
    for line_lst in read_file():#调用read_file()生成器函数
        num = name_value[con_name]  #age的值是2 num = 2
        if eval(condition):#eval使字符串里的代码运行 int(con_value) < int(line_lst[num]
            for col in col_l:  # ['name','age']
                print(line_lst[name_value[col]], end=' ')
#name_value[col]为2,3,取出line_lst列表索引为2,3的值
            print()

def select(sql):
    # sql = 'select name,age where age>20'
    col_l, con = format_sql(sql)   # 调用format_sql函数 col_l = ['name', 'age'],con = age>20
    if '>' in con:#判断比较符号是什么
        show(con,col_l,'>','int(con_value) < int(line_lst[num])')#调用show()函数,
    if '<' in con:
        show(con, col_l, '<', 'int(con_value) > int(line_lst[num])')
    if '=' in con:
        show(con, col_l, '=', 'con_value == line_lst[num]')
    if 'like' in con:
        show(con, col_l, 'like', 'con_value in line_lst[num]')


# 先判断一下是否是查操作
if sql.startswith('select'):
    # 是查找操作
    select(sql)#调用select函数
else:
    print('是其他操作')
class Base:
    def __init__(self):
        self.func()
    def func(self):
        print('in base')

class Son(Base):
    def func(self):
        print('in son')#in son

s = Son()
原文地址:https://www.cnblogs.com/pythonz/p/9982896.html