Python combines two address book texts into a text example using a dictionary,

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.