9-day9-大作业-生成器
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Q1mi" # Date: 2017/6/16 # 实现tail | grep 功能 import time def tail(filename): with open(filename, 'r', encoding='utf-8') as f: f.seek(0, 2) while True: line = f.readline() if line: yield line else: time.sleep(0.3) def grep(lines, pattern): print('lines', lines) for line in lines: if pattern in line: print(line) g = tail('a.txt') grep(g, 'error') # 设计实现 tail + grep + grep import time def tail(filename): with open(filename, 'r', encoding='utf-8') as f: f.seek(0, 2) while True: line = f.readline() if line: yield line else: time.sleep(0.4) t = tail('a.txt') def grep(lines, pattern): for line in lines: if pattern in line: yield line g = grep(t, 'alex') g_2 = grep(g, '3714') for xx in g_2: print(xx) # 2 文件b.txt内容 # apple 10 3 # tesla 100000 1 # mac 3000 2 # lenovo 30000 3 # chicken 10 3 # # 要求使用列表解析,从文件a.txt中取出每一行,做成下述格式 # [{‘name’:'apple','price':10,'count':3},{...},{...},...] with open("b.txt", "r", encoding="utf-8") as f: for line in f: print([{'name': line.strip().split()[0], 'price':line.strip().split()[1], 'count':line.strip().split()[2]} for line in f]) for i in [{'name':line.strip().split()[0],'price':line.strip().split()[1],'count':line.strip().split()[2]} for line in f]: print(i) # 4.周末大作业 # 周末大作业(见图): # 只实现作业要求的查询功能 # 增加,删除,修改功能为选做题 # 周末大作业 # SQL 1:select name,age from staff_table where age > 22 # SQL 2:select * from staff_table where dept = IT # SQL 3:select * from staff_table where enroll_date like 2013 import os def search(sql): sql_split_list = sql.split(" ") staff_info_keys = ["staff_id", "name", "age", "phone", "dept", "enroll-date"] if sql == ('select name,age from staff_table where age > %s' %(sql_split_list[7])): with open('abc.txt', 'r', encoding="utf-8") as f: list = [] for line in f: i = line.strip().split(",") name_age_list = [i[1], i[2]] if i[2] > sql_split_list[7]: list.append(name_age_list) for i in list: print(i) print("%s row in set" %len(list)) elif sql == ('select * from staff_table where %s like %s' % (sql_split_list[5],(sql_split_list[7]))): with open('abc.txt', 'r', encoding="utf-8") as f: list = [] for line in f: i = line.strip().split(',') j = i[5].split('-') if j[0] == sql_split_list[7]: list.append(i) for x in list: print(x) print("%s row in set" %len(list)) else: with open('abc.txt', 'r', encoding="utf-8") as f: list = [] for line in f: i = line.strip().split(",") if sql == ('select * from staff_table where %s = %s' % (sql_split_list[5], i[(staff_info_keys.index(sql_split_list[5]))])): list.append(i) else: continue for j in list: print(j) print("%s row in set" %len(list)) tag = True while tag: sql = input("请输入SQL语句(q quit): ").strip() if sql != 'quit': search(sql) else: tag = False