源代码:# dict1 是 字典 , 用来对应相应元素的下标,我们将文件转成列表,对应的也就是文件的下标,通过下标来找文件元素dict1 = {'sort':0 , 'name':1 ,'age':2 ,'phone':3 ,'job':4 }#将最后需要打印的信息转成列表的形式def p_message(m1): if '*' in m1: m1 = dict1.keys() return m1 m1 = m1.split(',') for i in range(len(m1)): m1[i] =m1[i].strip() return m1#遍历文件信息,将其转化成列表的形式#将函数转化成生成器,好处是不用一次将文件信息全部传入内存,而是用多少传多少def op_file(m2): m2 = m2.strip() with open(m2 ,encoding='utf=8')as f: for line in f: line = line.strip() line = line.split(',') yield line#进行条件筛选def choose(pp1 ,m3): lis = [] m3 = m3.strip() if '>' in m3: c1 ,c2 = m3.split('>') c1 = c1.strip() c2 = c2.strip() g = op_file(m2) for line_lis in g: if int(line_lis[dict1[c1]]) > int(c2): li = [] for l_list in pp1: li.append(line_lis[dict1[l_list]]) lis.append(li) for i in lis: print(i) if '<' in m3: c1,c2 = m3.split('<') c1 = c1.strip() c2 = c2.strip() g = op_file(m2) for line_lis in g: if int(line_lis[dict1[c1]]) < int(c2): li = [] for l_list in pp1: li.append(line_lis[dict1[l_list]]) lis.append(li) for i in lis: print(i) if '=' in m3: c1, c2 = m3.split('=') c1 = c1.strip() c2 = c2.strip() g = op_file(m2) for line_lis in g: if c2 in line_lis[dict1[c1]]: li = [] for l_list in pp1: li.append(line_lis[dict1[l_list]]) lis.append(li) for i in lis: print(i)#分析输入的条件信息while 1: message = input('>>>') # message = 'select name ,age from info where age > 22 ' # m1 : 我们所要最后打印的信息 m2 : 文件名 m3 : 筛选条件 m1 , m3 = message.split('where') m1 , m2 = m1.split('from') m1 = m1.replace('select',' ').strip() #pp1 是 修改完的m1 pp1 = p_message(m1) op_file(m2) choose(pp1 ,m3)文件内容:
1,Alex,22,13651054608,IT2,Egon,23,13304320533,Tearcher3,nezha,25,1333235322,IT
来源:博客园
作者:如果可以,我选择忘记
链接:https://www.cnblogs.com/if-it-is-possible/p/11519636.html