1 #!/usr/bin/env python
2 #_*_ coding:UTF-8 _*_
3 #__auth__: Dalhhin
4 #Python 3.5.2,Pycharm 2016.3.2
5 #2017/05/15
6
7 importsys,os8
9 def where(dbfile,where_list): #条件是一个list
10
11 defand_or_where(sub_where_list):12 '''获取and或同时含有and、or关键字的条件'''
13 and_list =[]14 or_list =[]15 for i insub_where_list:16 if i == 'and':17 and_index =sub_where_list.index(i)18 and_list_temp1 =sub_where_list[:and_index]19 and_list_temp2 = sub_where_list[and_index + 1:]20 if 'or' inand_list_temp1:21 and_list.append(and_list_temp2)22 or_index = and_list_temp1.index('or')23 or_list.append(and_list_temp1[:or_index])24 and_list.append(and_list_temp1[or_index + 1:])25 break
26 if 'or' inand_list_temp2:27 and_list.append(and_list_temp1)28 or_index = and_list_temp2.index('or')29 and_list.append(and_list_temp2[:or_index])30 or_list.append(and_list_temp2[or_index + 1:])31 break
32 and_list.append(and_list_temp1)33 and_list.append(and_list_temp2)34 returnand_list,or_list35
36 defor_where(sub_where_list):37 '''获取只有or条件下的关键字条件'''
38 if len(sub_where_list) > 4:39 or_list =[]40 or_str_temp1 = ' '.join(sub_where_list)41 or_list_temp2 = or_str_temp1.split('or')42 for or_info inor_list_temp2:43 or_list.append(or_info.split())44 return 'or',or_list45 else:46 return 'or',sub_where_list47
48 defand_where(sub_where_list):49 '''获取只有and条件下的关键字条件'''
50 and_list =[]51 and_str = ' '.join(sub_where_list)52 and_list_temp = and_str.split('and')53 for and_info inand_list_temp:54 and_list.append(and_info.split())55 return 'and',and_list56
57 defnot_and_or_where(sub_where_list):58 '''获取无and和or关键字的时候的条件'''
59 par_list =[]60 par_list.append(sub_where_list)61 returnNone,par_list62
63 defnot_and_or_data(where_list):64 '''获取没有and和or条件时匹配到的数据'''
65 where_tiaojian = not_and_or_where(where_list) #交给函数处理,得到处理后的 条件元组
66 if 'not' not in where_tiaojian[1][0]: #当条件没有not关键字的时候
67 field_name, mark, value = where_tiaojian[1][0] #不取反那么就获取条件的字段,运算符,值
68 match_data = [] #用于存放匹配的数据,最后进行展示
69 with open(dbfile, encoding='UTF-8') as fd:70 for user_info infd:71 user_id, user_name, user_age, user_phone, user_job, user_date = user_info.strip().split(',')72 if field_name == 'id': #读取文件的每一行,判断条件的字段是否是id
73 if mark != '=': #不取反
74 if eval('%s %s %s' % (user_id, mark, value)): #针对条件字段,进行数据的过滤
75 match_data.append(user_info) #存储匹配的数据
76 continue
77 else:78 if user_id ==value:79 match_data.append(user_info)80 continue
81 elif field_name == 'age':82 if mark != '=':83 if eval('%s %s %s' %(user_age, mark, value)):84 match_data.append(user_info)85 continue
86 else:87 if user_age ==value:88 match_data.append(user_info)89 continue