查询语句的实现
def read_file(): '''读文件''' with open('userinfo','r') as f: for line in f: line_lst = line.strip().split(',') # ['1','Alex','22','13651054608','IT'] yield line_lst def filter_item(col,value,signal): '''筛选条件 col='age' 22 >''' #dic[col] == dic['age'] == 2 dic = {'id':0,'name':1,'age':2,'phone':3,'job':4} correct = [] #存储符合条件的行列表 for line_lst in read_file(): #['1','Alex','22','13651054608','IT'] age > 20 if signal == '>': if int(line_lst[dic[col]]) > int(value): correct.append(line_lst) elif signal == '<': if int(line_lst[dic[col]]) < int(value): correct.append(line_lst) elif signal == '=': if line_lst[dic[col]] == value: correct.append(line_lst) elif signal == 'like': if value in line_lst[dic[col]]: correct.append(line_lst) return correct def condition_an(con): # 分析条件 # 根据条件中的符号来进行操作: > < = like if '>' in con: # age > 22 col_name,value = con.split('>') #age,22 col_name = col_name.strip() #'age' value = value.strip() #'22' correct = filter_item(col_name,value,'>') # 筛选出来所有符合条件的项 elif '<' in con: # age < 22 col_name,value = con.split('<') #age,22 col_name = col_name.strip() #'age' value = value.strip() #'22' correct = filter_item(col_name,value,'<') # 筛选出来所有符合条件的项 elif '=' in con: # age < 22 col_name,value = con.split('=') #age,22 col_name = col_name.strip() #'age' value = value.strip() #'22' correct = filter_item(col_name,value,'=') # 筛选出来所有符合条件的项 elif 'like' in con: # age < 22 col_name,value = con.split('like') #age,22 col_name = col_name.strip() #'age' value = value.strip() #'22' correct = filter_item(col_name,value,'like') # 筛选出来所有符合条件的项 return correct def show(col,correct): # 展示符合条件的行中需要的字段 col = 'name,age,phone,job' '*' dic = {'id': 0, 'name': 1, 'age': 2, 'phone': 3, 'job': 4} if '*' == col.strip(): col_lst = dic.keys() #[id,name,age,phone,job] else: col_lst = col.split(',') #[name,age,phone,job] for i in correct: #i = ['1', 'Alex', '22', '13651054608', 'IT'] for col in col_lst: print(i[dic[col]],end=' ') print() # exp = input('>>>') exp = 'select * where phone like 133' # exp = 'select * where age>22' col,con = exp.split('where') # 要显示的列,条件 col = col.replace('select','').strip() print(col,con) correct = condition_an(con) #调用分析条件的函数 show(col,correct)