Example of merging two text files in Python and sorting alphabetically by initials

Source: Internet
Author: User
Before a period of time on the internet to see an interview question, the requirements are as follows:

Work number and name are recorded in the employee file

The code is as follows:


Cat Employee.txt:

Jason Smith

John Doe

Sanjay Gupta

Ashok Sharma


Record work number and salary in bonus file

The code is as follows:


Cat Bonus.txt:

100 $5,000

200

300 $3,000

400 $1,250


Request to merge two files and output as follows, processing the result:

The code is as follows:


Ashok Sharma $1,250

Jason Smith $5,000

John Doe

Sanjay Gupta $3,000


This is required to be written in the shell, but my shell is not very good, I use Python to achieve

Note that, according to the meaning of the title, in the output file also need to be sorted by the initials, implementation code

The code is as follows:


#! /usr/bin/env python
#coding =utf-8
FP01 = open ("Bonus.txt", "R")
A = []
For LINE01 in FP01:
A.append (LINE01)

FP02 = open ("Employee.txt", "R")

Fc02 = sorted (fp02, key = Lambda x:x.split () [1])

For LINE02 in FC02:
i = 0
While Line02.split () [0]!=a[i].split () [0]:
i + = 1
Print "%s%s%s"% (Line02.split () [0], Line02.split () [1], Line02.split () [2], A[i].split () [1])

Fp01.close ()
Fp02.close ()

  • Related Article

    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.