1
2
3
4
|
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day3$ more student_info.txt
stu1101 mingjia.xu
275896019
@qq.com
263
SystemAdmin
18810404260
stu1102 Yangjiansong jason@s156.com A8music SystemAdmin
13601247960
stu1103 zouxinkai zouxinkai_2006@
126
.com jishubu systemadmin
1861214111
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
#!/usr/bin/env python
staff_dic = {} #从文件中读取员工信息,并作为字典处理
f = file(
'student_info.txt'
)
for
line
in
f.xreadlines():
stu_id, stu_name, mail, company, title, phone = line.split() #取文件一行中每一列元素
staff_dic[stu_id] = [stu_name, mail, company, title, phone] #key值对应的Value值为一列表
while
True:
query = raw_input(
'\033[32;1mPlease input the query string:\033[0m'
).strip()
if
len(query) <
3
: #如果输入查询的字符少于
3
,则要求重新输入
print
'You have to input at least 3 letters to query!'
continue
match_counter =
0
#计数器,判断是否有匹配到员工信息
for
k,v
in
staff_dic.items(): #.items(),key值作为列表中,元组的左元素,key值(这里为列表)则作为右元素
index = k.find(query) #find()返回查询到字符串的首个字符的索引,找空串返回
0
,找不到返回-
1
if
k.find(query) != -
1
: #如果找到
print k[:index] +
'\033[32;1m%s\033[0m'
% query + k[index + len(query):],v #这里会有用户输入的内容进行颜色加深
match_counter +=
1
else
:
str_v =
'\t'
.join(v) #将列表中的元素连接为字符串
index = str_v.find(query) #方法如上面查找key值一样
if
index != -
1
:
print k,str_v[:index] +
'\033[32;1m%s\033[0m'
% query + str_v[index + len(query):]
match_counter +=
1
print
'Matched \033[31;1m%s\033[0m records!'
% (match_counter)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
Please input the query string:stu1101 ===>对员工号(键值)精确查询
stu1101 [
'mingjia.xu'
,
'275896019@qq.com'
,
'263'
,
'SystemAdmin'
,
'18810404260'
]
Matched
1
records!
Please input the query string:stu ===>对员工号(键值)模糊查询
stu1103 [
'zouxinkai'
,
'zouxinkai_2006@126.com'
,
'jishubu'
,
'systemadmin'
,
'1861214111'
]
stu1102 [
'Yangjiansong'
,
'jason@s156.com'
,
'A8music'
,
'SystemAdmin'
,
'13601247960'
]
stu1101 [
'mingjia.xu'
,
'275896019@qq.com'
,
'263'
,
'SystemAdmin'
,
'18810404260'
]
Matched
3
records!
Please input the query string:kai ===>对员工信息(value值)模糊查询
stu1103 zouxinkai zouxinkai_2006@
126
.com jishubu systemadmin
1861214111
Matched
1
records!
Please input the query string:zou
stu1103 zouxinkai zouxinkai_2006@
126
.com jishubu systemadmin
1861214111
Matched
1
records!
|