Python combines two address book texts into a text example using a dictionary,
In this example, the dictionary is used to merge two address book texts into one. The specific code is as follows:
Def main (): ftele1 = open ("d: \ TeleAddressBook.txt", "rb") ftele2 = open ("d: \ EmailAddressBook.txt", "rb") ftele1.readline () # skip the first line ftele2.readline () lines1 = ftele1.readlines () lines2 = ftele2.readlines () dic1 = {} dic2 = {} for line in lines1: # obtain the name and phone number in the first text. elements = line. split () # convert the read bytes in the text to str dic1 [elements [0] = str (elements [1]. decode ('gbk') for line in lines2: elements = line. split () dic2 [elements [0] = st R (elements [1]. decode ("gbk") lines = [] lines. append ("Name \ t phone \ t email \ 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. app End (s) ftele3 = open ("d: \ dizhibook.txt", "w") ftele3.writelines (lines) ftele3.close () ftele2.close () ftele1.close () print ("The dizhibook are merged! ") Main ()
Demo result:
Summary
The preceding section describes how to use a dictionary to merge the two address book texts into a text example. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!