本文实例主要实现的是利用字典将两个通讯录文本合并为一个文本,具体代码如下:
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
def main():
ftele1 = open ( "d:\TeleAddressBook.txt" , "rb" )
ftele2 = open ( "d:\EmailAddressBook.txt" , "rb" )
ftele1.readline() #跳过第一行
ftele2.readline()
lines1 = ftele1.readlines()
lines2 = ftele2.readlines()
dic1 = {}
dic2 = {}
for line in lines1: #获取第一个文本中的姓名和电话信息
elements = line.split()
#将文本中的读出来的bytes转换为str
dic1[elements[ 0 ]] = str (elements[ 1 ].decode( 'gbk' ))
for line in lines2:
elements = line.split()
dic2[elements[ 0 ]] = str (elements[ 1 ].decode( "gbk" ))
lines = []
lines.append( "姓名\t 电话\t 邮箱\n" )
for key in dic1:
s = ''
if key in dic2.keys():
s = '\t' .join([ str (key.decode( 'gbk' )),dic1[key],dic2[key]])
s + = '\n'
else :
s = '\t' .join([ str (key.decode( 'gbk' )),dic1[key], str ( ' ---- ' )])
s + = '\n'
lines.append(s)
for key in dic2:
s = ''
if key not in dic1.keys():
s = '\t' .join([ str (key.decode( 'gbk' )), str ( ' ---- ' ),dic2[key]])
s + = '\n'
lines.append(s)
ftele3 = open ( "d:\dizhibook.txt" , "w" )
ftele3.writelines(lines)
ftele3.close()
ftele2.close()
ftele1.close()
print ( "The dizhibook are merged!" )
main()
|
演示结果:
总结
以上就是本文关于Python利用字典将两个通讯录文本合并为一个文本实例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
原文链接:http://blog.csdn.net/m0_38066258/article/details/77113007