[root@cheeron lesson1]# cat user.txt
1 cheeron python 4099822
2 forilen shell 12309865
3 XueLi JS 4321780
4 LiLei IT 48393022
5 Simith IT 2340987
6 Liudehua Python 1234567
7 cheeron python 4099822
8 forilen shell 12309865
9 XueLi JS 4321780
10 LiLei IT 48393022
11 Simith IT 2340987
12 Liudehua Python 1234567
#!/usr/bin/env python staff_list = 'user.txt' f = open(staff_list) c = f.readlines() while True: user_input = raw_input('\033[32;1mPls input sth to search:\033[0m ').strip() if len(user_input) == 0: continue for line in c: if user_input in line: print line break else: print '\033[31;1mnot a vaild input!\033[0m'
解决1次只匹配单行的问题,增加一个key,作为信号量,当匹配时则为key赋值为1,否则为0.
1 #!/usr/bin/env python 2 staff_list = 'user.txt' 3 f = open(staff_list) 4 c = f.readlines() 5 while True: 6 user_input = raw_input('\033[32;1mpls input sth to search:\033[0m ').strip() 7 if len(user_input) == 0:continue 8 key=0 9 for line in c: 10 if user_input in line: 11 print line 12 key=1 13 if key == 0: 14 print '\033[31;1mnot a vaild key word!\033[0m'
结果:
pls input sth to search: LiLei 4 LiLei IT 48393022 10 LiLei IT 48393022 pls input sth to search: