Python-Old-Version/C2/Handling-large-files/English

From Script | Spoken-Tutorial
Revision as of 18:30, 27 November 2012 by Chandrika (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Hello and welcome to the tutorial on handling large data files and processing them.

Up until now we have covered:

  • How to create plots.
  • How to read data from files and process it.

In this tutorial, we shall use these concepts and some new ones, to solve a problem/exercise.

We have a file named sslc.txt on our desktop. It contains record of students and their performance in one of the State Secondary Board Examination. It has *180, 000* lines of record. We are going to read it and process this data. We can see the content of file by double clicking on it. It might take some time to open since it is quite a large file. Please don't edit the data. This file has a particular structure. Each line in the file is a set of 11 fields separated by semi-colons. Consider a sample line from this file.

A;015163;JOSEPH RAJ S;083;042;47;AA;72;244;;;

The following are the fields in any given line.

  • Region Code which is 'A'
  • Roll Number 015163
  • Name JOSEPH RAJ S
  • Marks of 5 subjects:
 ** English 083
 ** Hindi 042
 ** Maths 47
 ** Science AA (Absent)
 ** Social 72
  • Total marks 244
  • Pass/Fail - This field is blank here because the particular candidate was absent for an exam if not it would've been one of (P/F)
  • Withheld - Again blank in this case(W)

Let us now look at the problem we wish to solve: Draw a pie chart representing the proportion of students who scored more than 90% in each region in Science.

This is the result we expect:

In order to solve this problem, we need the following machinery:

  • File Reading - which we have already looked at.
  • parsing - which we have looked at partially.
  • Dictionaries - we shall be introducing the concept of dictionaries here.
  • And finally plotting - which we have been doing all along.

Since this file is on our Desktop, let's navigate by typing

cd Desktop

Let's get started, by opening the IPython prompt by typing,

ipython -pylab

Let's first start off with dictionaries.

We earlier used lists briefly. Back then we just created lists and appended items into them.

x = [1, 4, 2, 7, 6]

In order to access any element in a list, we use its index number. Index starts from 0. For eg. x[0] gives 1 and x[3] gives 7.

But, using integer indexes isn't always convenient. For example, consider a telephone directory. We give it a name and it should return a corresponding number. A list is not well suited for such problems. Python's dictionaries are better, for such problems. Dictionaries are just key-value pairs. For example:

d = {'png' : 'image',
     'txt' : 'text', 
     'py' : 'python'} 

And that is how we create a dictionary. Dictionaries are created by typing the key-value pairs within flower brackets.

d

d is a dictionary. The first element in the pair is called the `key' and the second is called the `value'. The key always has to be a string while the value can be of any type.

Lists are indexed by integers while dictionaries are indexed by strings. They are indexed using their keys as shown

In []: d['txt']
Out[]: 'text'
In []: d['png']
Out[]: 'image'

The dictionaries can be searched for the presence of a certain key by typing

'py' in d
True
'jpg' in d
False

Please note that keys, and not values, are searched. 'In a telephone directory one can search for a number based on a name, but not for a name based on a number' to obtain the list of all keys in a dictionary, type

d.keys()
['py', 'txt', 'png']

Similarly,

d.values()
['python', 'text', 'image']

is used to obtain the list of all values in a dictionary One more thing to note about dictionaries, in this case for d,

d  

is that dictionaries do not preserve the order in which the items were entered. The order of the elements in a dictionary should not be relied upon.



Parsing and string processing

As we saw previously we shall be dealing with lines with content of the form

A;015162;JENIL T P;081;060;77;41;74;333;P;;

Here ';' is delimiter, that is ';' is used to separate the fields. We shall create one string variable to see how can we process it to get the desired output.

line = 'A;015162;JENIL T P;081;060;77;41;74;333;P;;'

Previously we saw how to split on spaces when we processed the pendulum.txt file. Let us now look at how to split a string into a list of fields based on a delimiter other than space.

a = line.split(';')

Let's now check what 'a' contains.

a

is list containing all the fields separately. a[0] is the region code, a[1] the roll no., a[2] the name and so on. Similarly, a[6] gives us the science marks of that particular region.

So we create a dictionary of all the regions with number of students having more than 90 marks.


Let's now start off with the code. We first create an empty dictionary

science = {}

now we read the records, one by one from the file sslc.txt

for record in open('sslc.txt'):

we split each record on ';' and store it in a list by:

    fields = record.split(';')

now we get the region code of a particular entry by

    region_code = fields[0].strip()

The strip() is used to remove all leading and trailing white spaces from a given string now we check if the region code is already there in dictionary by typing

   if region_code not in science:

when this statement is true, we add new entry to dictionary with initial value 0 and key being the region code.

       science[region_code] = 0
      

Note that this if statement is inside the for loop so for the if block we will have to give additional indentation. we again come back to the older, 'for' loop's, indentation and get the science marks by

   score_str = fields[6].strip()

we check if student was not absent

   if score_str != 'AA':

then we check if his marks are above 90 or not

      if int(score_str) > 90:

if yes we add 1 to the value of dictionary for that region by

      	  science[region_code] += 1

Hit return twice to exit the for loop

by end of this loop we shall have our desired output in the dictionary 'science' we can check the values by

science

now to create a pie chart we use

pie(science.values(),labels = science.keys())

the first argument to the pie function is the values to be plotted. The second is an optional argument which is used to label the regions.

title('Students scoring 90% and above in science by region')
savefig('science.png')

That brings us to the end of this tutorial. We have learnt about dictionaries, some basic string parsing and plotting pie chart in this tutorial. Hope you have enjoyed it. Thank you.

Contributors and Content Editors

Chandrika