Python – write code to open a txt file and get outputs for parts a,



Several data files are also present: Patients.txt, Diagnoses.txt, Labs.txt, and Admissions.txt.

Please note that each data file has a columns descriptor line as the first line of the file.  When processing, we must IGNORE that line as it is obviously not valid data. The following code preceding the actual loop that reads the file does just that. Each time you read a file containing that header line you must include this code.

fhand = open('Diagnoses.txt')    # open the file, establish the file handle

fhand.readline()                 # read the first line and ignore it
# declare and set any initialization variables here, such as counters, lists, dictionaries

for line in fhand:         # loop through the file line by line 

Part A

What patient (by ID) has the most admissions? 

1. Open, rename it, and run it. It should display the ID field from all the lines in the file Admissions.txt. Comments included therein guide your code development.

2. Run and study the code in Ch 9 code sample 13. It provides most of what you need for this task. (PLEASE ATTACHED FILE PART A.JPG FOR CODE SAMPLE)

Part B 

What are the 10 patients (by ID) having the most labs? 

1. To tackle this task, repeat the code you wrote in 12a to create a dictionary containing IDs and the count of those IDs, this time on the Labs.txt file.

2. Then employ the strategies used in Ch 10 code sample 10 (ten most common words) to create a list of tuples, sort the list, and then print the first ten.


Part C 

Of the top 10 patients with the most labs, how many are male? Print their IDs and print the number of males in the top 10.

1. Repeat the code you wrote in 12b to create a dictionary containing IDs and the count of those IDs, create the list, and sort the list in reverse.

2. Now you have to find out which of the top 10 in the list of most Labs are male. To do that, you have to loop through the Patients.txt file, checking to see if the ID is present in the same line as the word ‘Male’.

3. Follow the comments in the code to add the statements necessary to achieve the tasks. Don’t be afraid to add print statements to help you write the code; remove them when you’re finished. The output is shown below.