Escolar Documentos
Profissional Documentos
Cultura Documentos
INFORMATION
TECHNOLOGY
Search engine For a book
Text book for semister -5
AP IIIT BASARA
ADILABAD
Go to Index
INDEX
This book contins the modules
MODULE NAME
PAGE NO:
Go to Index
Go to Index
the modules in this course are to be attempted sequentially, as there is an inherent link
between each one of them.
Go to Index
Module 1:
Count the Number of Words
Strings
A string is simply a list of characters in order. A character is anything you can type on the keyboard
in one keystroke, like a letter, a number, or a backslash. For example, "hello" is a string. It is five
characters long h, e, l, l, o. Strings can also have spaces: "hello world" contains 11 characters,
including the space between "hello" and "world".
There are no limits to the number of characters you can have in a string you can have anywhere
from one to a million or more. You can even have a string that has 0 characters, which is usually
called "the empty string."
There are three ways you can declare a string in Python: single quotes ('), double quotes ("), and
triple quotes ("""). In all cases, you start and end the string with your chosen string declaration. For
example:
print ('I am a single quoted string')
I am a single quoted string
print ("I am a double quoted string")
I am a double quoted string
print ("""I am a triple quoted string""")
I am a triple quoted string
5
Go to Index
Go to Index
Go to Index
Go to Index
Go to Index
10
Go to Index
Module 2:
Count the Number of Words in a given File
Splitting a sentence
We hope that you have learnt about what is a string, taking input string and printing strings in the
module 1 and also you have used split() function to count number of words in the given string. Here
we are going to learn how to open a file ,read and count number of words, spaces, lines.. etc in a
given file.
Before we are going to read a file you need to know about split()and count() functions. The standard
split() can use only one delimiter. To split a text file into words you need multiple delimiters like
blank, punctuation, math signs (+-*/), parentheses and so on.
Here's a quick some example to understand
Spliting a sentence:
sent = "Jack ate the apple." # Assign a stament to a variable
splitsent = sent.split(' ') # spliting a stament
print splitsent # printing the data in after spliting
Output: ['Jack', 'ate', 'the', 'apple.']
when we split a statement, that will be converted into a list and every word is stored as an element
11
Go to Index
Go to Index
Reading a file
Files in a programming sense are really not very different from files that you use in a word
processor or other application: you open them, do some work and then close them again.
You can open files with open function, which has the following syntax
Open(name[,mode])
Open() takes two arguments. The first is the filename (which may be passed as a variable or a literal
string and mandatory). The second is the mode which is optional. The mode determines whether we
are opening the file for reading(r) or writing(w).
Ex: file = open(text1.txt, r) # This is in reading mode
We close the file at the end with the close() method.
Ex: file.close()
Heres a quick example to understand. See that there is a txt file which contains Hello world!
statement in it.
f = open('somefile.txt', 'r') # open file in reading mode
print f.read() # reading the data
'Hello, World!'
We can assign data to a variable and it will be consider as a string.
f = open('somefile.txt', 'r') # open file in reading mode
13
Go to Index
14
Go to Index
Go to Index
16
Go to Index
Module 3:
Reading Text from Multiple Files
Readings Text from Multiple Files
So far we have covered how to open a text file, read the text, counting the words and closing the
file. Now in this module we will learn how to read multiple text files by using single text file.
Let us see an example to read the text from multiple files
Worked out example :
We have a file 'list.txt' having text one file name file1.txt and file2.txt. Some text has been included
to those two files.
Write a program to read the text in file1.txt , file2.txt and print the text.
list.txt contains following text :
file1.txt
file2.txt
file1.txt contains following text:
This is file1. Here I am adding some text.
file2.txt contains following text:
17
Go to Index
18
Go to Index
19
Go to Index
Module 4:
Accessing Values in Strings
20
Go to Index
-5 -4
-3
-2
-1
>>>print s[2] #To print the Middle character you can also write s[len(s)/2]
We can also use some predefined string functions. See the below table
Common string operations
Here is a table:
String Method
Description
Example
>>> s=India >>>
Go to Index
g)
s.find("d") 2
end. Returns -1 if sub is not found
>>> x=string
print x.startswith(s) #
True
2) Count the number of words which starts with character in the given string
char=raw_input("Enter a charcter:")
words=s.split()
count=0
if words[i].startswith(char):
count=count+1
22
Go to Index
23
Go to Index
Module 5:
String Slicing
String Slicing
Reading Material:
In the previous modules we have seen how to access the characters in the string and how to access a
file. Now it is very easy to access the last letter of any string from the file chapter.
To access the last character we can use two methods
1) Slicing
Python supports reading part, or a slice, of a larger string:
>>> s = "Peter, Paul, and Mary"
>>> print s[0:5]
Peter
>>> print s[7:11]
Paul
>>> print s[17:21]
Mary
The operator [n:m] returns the part of the string from the nth character to the mth character,
including the first, but excluding the last.
24
Go to Index
Go to Index
Go to Index
27
Go to Index
Module 6:
Count the number occurrences
28
Go to Index
Go to Index
30
Go to Index
31
Go to Index
32
Go to Index
33
Go to Index
Module 7:
Count the given bigram
Count the given bigram
In the previous module we have learned how to find unigram in a file consists of multiple files. In
this module we are going work out to count the given bigram.
Let us look at what is a bigram:
string=this is a bigram program
As we have done in the previous module every word in the above string is called unigram. And a
bigram is two consecutive letters or words or syllables separated by single space.
Bigrams in above string :
this is
is a
a bigram
bigram program
Worked out example:
Write a program to find given bigram is present there in the string or not.
string=hello good morning to all
search=good morning
34
Go to Index
count=count+1
else:
continue
if count==0:
35
Go to Index
else:
Method 2:
text="hello good morning to all"
ch="good morning"
print text.count(ch) # count is a built in function
36
Go to Index
Module 8:
Trigram concept
Trigram concept
(Trigram concept)
Reading Material:
In the previous module we have learned how to find unigram and bigram in a file consists of
multiple files. In this module we are going to find trigram.
Let us look at what is a trigram:
Example:- string this is a trigram python program
As we have done in the previous module every word in the above string is called unigram, a bigram
is two consecutive letters or words or syllables separated by single space and a trigram constists aof
three letters or words separated by a single space.
Trigrams in above string:
this is a
is a trigram
a trigram python
trigram python program
Worked out example:
37
Go to Index
38
Go to Index
39
Go to Index
Module 9:
Counting vowels in the text
Counting vowels in the text
40
Go to Index
41
Go to Index
Module 10:
Dictionary
Operations on Dictionaries
Operations on Dictionaries
The operations on dictionaries are somewhat unique. Slicing is not supported, since the items have
no intrinsic order.
>>> d = {'a':1,'b':2, 'cat':'Fluffers'}
>>> d.keys()
['a', 'b', 'cat']
>>> d.values()
[1, 2, 'Fluffers']
>>> d['a']
1
>>> d['cat'] = 'Mr. Whiskers'
>>> d['cat']
'Mr. Whiskers'
>>> 'cat' in d
True
42
Go to Index
Dictionary
Let us rewind what we learned in the previous module. In the previous module we have learned
43
Go to Index
Go to Index
45
Go to Index
Module 11:
Hash Table
Hash Table
KEY Value
Name1 Value1
Name2 Value2
Name3 Value3
There is no strict rule as to when, where, why, or how to use a hash table. Everything depends on
the programmer. For example, it can be used to create a list that would replace a 2-dimensional
array.
Example for referring a value to a string:
>>>String="word"
>>> value=ord(string[0])+ord(string[1])+ord(string[2])+ord(string[3])
>>>print value
46
Go to Index
Dictionaries:
A dictionary is mutable and is another container type that can store any number of Python objects,
including other container types.
Dictionaries consist of pairs (called items) of keys and their corresponding values.
Python dictionaries are also known as associative arrays or hash tables. The general syntax of a
dictionary is as follows:
It is best to think of a dictionary as an unordered set of key: value
pairs, with the requirement that the keys are unique (within one dictionary). A
pair of braces creates an empty dictionary: {}. Placing a comma-separated list
of ''key: value'' pairs within the braces adds initial key: value pairs to the
dictionary; this is also the way dictionaries are written on output.
47
Go to Index
Go to Index
49
Go to Index
50
Go to Index
51
Go to Index
Module 12:
Counting bigrams in a text file
52
Go to Index
# creating dic
for i in range(len(sa)-1):
not
d[a]=d[a]+1 # if so incrementing bigram
value
else:
d[a]=1
print d
# printing dictionary
Out put:
{'is Ramu': 1, 'this is': 2, 'Ramu this': 1, 'is raju': 1}
53
Go to Index
Module 13:
Comparing two
words with the same length
Worked Example 1 :
S1 = 'RAVI'
S2 = 'ravi'
print cmp(S1,S2)
Output : -1
By this we can find the condition. -1 for S1<S2.
Worked Example 2 :
------- S1 = 'ramu'
S2 = 'raju'
print cmp(S1,S2)
Output: 1 -------
54
Go to Index
55
Go to Index
Go to Index
57
Go to Index
58
Go to Index
Module 14:
Compare two
different length strings
Compare two different length strings
Compare two different length strings
From the previous module you have learnt how to compare two strings when the lengths are same.
Now you are going to work on the same but with different lengths.
Python Tells it Straight: Size Matters
It's true; Python is a size queen. It's obsessed with comparing strings, numbers, you name it. It may
not make a lot of sense, though, as to how Python sees the value of different strings (uppercase Z is
less than lowercase A).
To compare the size of strings, we use the < and > comparison operators. It should return a True or
False, depending upon whether or not the comparison is.
The rules for which strings are bigger is like so:
Letters at the start of the alphabet are smaller than those at the end
Capital letters are smaller than lowercase letters
Numbers are smaller than letters
59
Go to Index
60
Go to Index
Example Programs
Worked out example:
a=raw_input("Enter a value=")
b=raw_input("enter b value=")
sum1=sum2=0
for i in range(len(a)):
** sum1=sum1+ord(a[i])** sum2=sum2+ord(b[i])
if sum1<sum2:
print "-1"
elif sum1==sum2:
print "0"
else:
print "1"
61
Go to Index
Module 15:
Sorting of three strings
Example Programs
Worked out Example:
Sorting of two strings in ascending order.
Input: s1=rgukt,s2=iiit
Program:
print s2
print s1
else:
print s1
print s2
Output:
iiit
rgukt
62
Go to Index
Sort function
Sorting of three strings
In the previous module, we learn comparison of two strings of the same length and different length.
Using the same logic we can sort the strings. We will learn sorting of three strings in this module.
We have the python built in functions to sort the given list like 'sort' and 'sorted'. We will know
about these functions below.
Sort function:
This is a python built in function to sort the list. The list may contain characters, strings and
numbers. When ever we sort a list the list will be changed to sorted list.
Example 1:
s=['a','z','e','s','q']
s.sort()
#sorting of
print s
Output:
['a', 'e', 'q', 's', 'z']
Sorts strings in a way that seems natural to humans. If the strings contain integers, then the integers
also taken as strings.
Example 2:
>>> s=['Team 11', 'Team 3', 'Team 1']
>>> s.sort()
>>> print s
['Team 1', 'Team 11', 'Team 3']
63
Go to Index
Sorted function
Sorted function:
The easiest way to sort is with the sorted(list) function, which takes a list and returns a new list with
those elements in sorted order. The original list is not changed. It's most common to pass a list into
the sorted() function, but in fact it can take as input any sort of iterable collection. The older
list.sort() method is an alternative detailed
Example 3:
s=['a','z','e','s','q']
print sorted(s)
Output:
['a', 'e', 'q', 's', 'z']
We have learned how to sort a list or strings using built in functions. It is very easy if we use the
built in function but we might not have improved logical skills. So, let us try with out using built in
function. To compare two strings we use cmp()function. You might have compared with the less
than or greater than operator or equal operator. Which works fine in python but not in other
programming languages. So, to be flexible for other programming languages we should use
respective function to compare not the operator. As we have cmp() function in python.
64
Go to Index
THANK YOU
BETA -6
65
Go to Index