File handling 18: Files and dictionary, Histogram, character frequency

# Write a program that creates a dictionary
# of the frequency of all characters in a file.
# display five most frequently occuring characters

# Files, Dictionary and Command line arguments
# Histogram - Character frequency

import sys
import operator

fname = sys.argv[1]
fs = open(fname, "r")

Char_freq = {}

while(True):
    Line = fs.readline().strip().lower()
   
    if not Line:
        break
   
    for ch in Line:
        if (ch.isalpha()):
            if ch in Char_freq:
                Char_freq[ch] += 1
            else:
                Char_freq[ch] = 1
           
for ch in Char_freq:
    print(ch, Char_freq[ch])

List1 = sorted(Char_freq.items(), key=operator.itemgetter(1), reverse=True)

print("Five most frequently occuring characters :")
for k,v in List1[0:5]:
    print(k,v)

fs.close()

File Handling 19: Name and phone number

# Given a file containing customer names and their phone numbers, 
# write a program to find the telephone number of a given customer.

# Files: Name and phone number
import sys

fname = sys.argv[1]
fs = open(fname,"r")
Flag = False

Name = input("Enter name :")
Name = Name.strip().lower()

while(True):
    line = fs.readline()
   
    if not line:
        break
   
    L = line.split(" ")
    if(L[0].strip().lower() == Name):
        Flag = True
        print("Name =", Name.capitalize())
        print("Phone number =", L[1])
        break

if(Flag==False):
    print(Name, "- Name not found in directory")
fs.close()

File handling 20: Compare two files and print the line where they differ

# Files: Difference between files

import sys

try:
    fname1 = sys.argv[1]
    fname2 = sys.argv[2]

    fs1 = open(fname1,"r")
    fs2 = open(fname2,"r")
    Flag = False
  
    L1 = fs1.readlines()
    L2 = fs2.readlines()

    nlines = min(len(L1), len(L2))

    for idx in range(0, nlines, 1):
        if (L1[idx] != L2[idx]):
            print("Files differ at line number", idx+1)
            Flag = True
            break
          
    if(Flag == False):
        if(len(L1)==len(L2)):
            print("Files are the same. They do not differ")
        else:
            print("Files differ at line number", nlines+1)
except:
    print("Error")
  
finally:  
    fs1.close()
    fs2.close()



File Handling 17: Files and Dictionary: Histogram, Word Frequency, remove noise words

# Write a program that creates a dictionary
# of the frequency of all words in a file.

# Files, Dictionary and Command line arguments
# Histogram - Word frequency

import sys

fname = sys.argv[1]
fs = open(fname, "r")

Word_freq = {}

while(True):
new_Line = ""
Line = fs.readline().strip().lower()

if not Line:
break

for ch in Line:
if (ch.isalpha() or ch.isspace()):
new_Line+=ch
L = new_Line.split(" ")

for wd in L:
if wd in Word_freq:
Word_freq[wd] += 1
else:
Word_freq[wd] = 1

for ele in Word_freq:
print(ele.ljust(15), Word_freq[ele])

print("Number of unique words in file = ", len(Word_freq))

fs.close()




# Write a program that creates a dictionary
# of the frequency of all words in a file.
# Remove noise words in file like a, an, the etc

# Files, Dictionary and Command line arguments
# Histogram - Word frequency

import sys

fname = sys.argv[1]
fs = open(fname, "r")

Word_freq = {}

Noise_words = ['an', 'as', 'of', 'it','by',  'to', 'so', 'do', 'be', 'up', 'on', 'ie', 'its', 'are', 'all', 'has', 'can', 'how', 'end', 'any', 'may', 'for', 'will', 'use', 'one', 'two', 'the', 'also', 'have', 'this', 'that', 'what', 'where', 'when', 'then', 'those', 'from', 'once', 'more', 'most' ]

while(True):
new_Line = ""
Line = fs.readline().strip().lower()

if not Line:
break

for ch in Line:
if (ch.isalpha() or ch.isspace()):
new_Line+=ch
L = new_Line.split(" ")

for wd in L:
if (len(wd)<=1 or wd in Noise_words):
continue

if wd in Word_freq:
Word_freq[wd] += 1
else:
Word_freq[wd] = 1

for ele in Word_freq:
print(ele.ljust(15), Word_freq[ele])

print("Number of unique words in file = ", len(Word_freq))

fs.close()

File handling 16: Replace a word in file

# Replace a word in a file

fs = open("ipt.txt", "r+")
old_str = input("Enter string to replace : ").strip()
new_str = input("Enter new string : ").strip()

Line = fs.read()
Line = Line.replace(old_str, new_str)

fs.seek(0,0)
fs.truncate()
fs.write(Line)

fs.seek(0,0)
Line = fs.read()
print(Line)

fs.close()

File Handling 15: Delete word in file

# Delete a word in a file

fs = open("ipt.txt", "r+")
search_str = input("Enter string to search : ").strip()

Line = fs.read()
Line = Line.replace(search_str, "")

fs.seek(0,0)
fs.truncate()
fs.write(Line)

fs.seek(0,0)
Line = fs.read()
print(Line)

fs.close()

File handling 14: display line containing word in file

# Search if a word exists in a file.
# Display all lines in which the word exists.

fs = open("ipt.txt", "r")
search_str = input("Enter string to search : ").strip().lower()
Flag = False

while(True):
Line = fs.readline().strip().lower()

if not Line:
break

if (search_str in Line):
Flag = True
print(Line)

if(Flag==False):
print(search_str, "not present in file")

fs.close()

File Handling 13: Count number of occurances of a word in a file

# Count number of times a word exists in a file

fs = open("ipt.txt", "r")
search_str = input("Enter string to search : ").strip().lower()
counter = 0

while(True):
Line = fs.readline().strip().lower()

if not Line:
break

counter += Line.count(search_str)

if(counter):
print(search_str, "present in file", counter , "times")
else:
print(search_str, "not present in file")

fs.close()

File handling 12: file word search

# Search if a word exists in a file.

fs = open("ipt.txt", "r")
search_str = input("Enter string to search : ").strip()
Flag = False

while(True):
Line = fs.readline().strip()

if not Line:
break

if (search_str in Line):
Flag = True
break

if(Flag==True):
print(search_str, "present in file")
else:
print(search_str, "not present in file")

fs.close()

File Handling 11: File line, word and character count

# Count number of characters, words and lines in a file
# File Count

fs = open("ipt.txt", "r")

charcount = 0
wordcount = 0
linecount = 0

all_lines = fs.readlines()
linecount = len(all_lines)

for Line in all_lines:
Line = Line.strip().lower()

tmp = Line.split(" ")
wordcount += len(tmp)

for ch in Line:
if(ch.isalpha()):
charcount += 1

print("Number of characters in file =", charcount)
print("Number of words in file =", wordcount)
print("Number of lines in file =", linecount)

fs.close()

File Handling 10: Merge files

# Merge two files

fs1 = open("ipt1.txt", "r")
fs2 = open("ipt2.txt", "r")
fd = open("opt.txt", "w+")

while(True):
Line = fs1.readline()
if not Line:
break
fd.write(Line)

while(True):
Line = fs2.readline()
if not Line:
break
fd.write(Line)

print("Files merged")
print("Displaying new file:")
fd.seek(0,0)
while(True):
Line = fd.readline()
if not Line:
break
print(Line)

fs1.close()
fs2.close()
fd.close()

# Merge two files

fs1 = open("ipt1.txt", "r")
fs2 = open("ipt2.txt", "r")
fd = open("opt.txt", "w+")

L1 = fs1.readlines()
L2 = fs2.readlines()

for Line in L1:
fd.write(Line)
for Line in L2:
fd.write(Line)

print("Files merged")
print("Displaying new file:")
fd.seek(0,0)
L = fd.readlines()
for Line in L:
print(Line)

fs1.close()
fs2.close()
fd.close()

File Handling 8: copy first n lines of a file, copy from nth line to mth line in a file

# Copy first n lines of a file

fs = open("ipt.txt", "r")
fd = open("opt.txt", "w+")

nlines = int(input("Enter number of lines to copy : "))
counter = 0

while(True):
if(counter == nlines):
break

Line = fs.readline()

if not Line:
break

fd.write(Line)
counter += 1

print("file copied")


print("displaying copied file:")
fd.seek(0,0)
while(True):
Line = fd.read()
if not Line:
break
print(Line)

fs.close()
fd.close()


# Copy first n lines of a file

fs = open("ipt.txt", "r")
fd = open("opt.txt", "w+")

nlines = int(input("Enter number of lines to copy : "))

L = fs.readlines()
for Line in L[0:nlines]:
fd.write(Line)

print("file copied")

print("displaying copied file:")
fd.seek(0,0)

L = fd.readlines()
for Line in L:
print(Line)

fs.close()
fd.close()


File Handling 7: Copy File

# Copy file

fs = open("ipt.txt", "r")
fd = open("opt.txt", "w+")

while(True):
Line = fs.readline()
if not Line:
break
fd.write(Line)

print("file copied")

print("displaying copied file:")
fd.seek(0,0)
while(True):
Line = fd.readline()
if not Line:
break
print(Line)

fs.close()
fd.close()


# Copy file

fs = open("ipt.txt", "r")
fd = open("opt.txt", "w+")

L = fs.readlines()
for Line in L:
fd.write(Line)

print("file copied")

print("displaying copied file:")
fd.seek(0,0)

L = fd.readlines()
for Line in L:
print(Line)

fs.close()
fd.close()

File Handling 6: Display from nth to mth line in a file

# Display from nth line to mth line of a file
# Use command line arguments

import sys

fname = sys.argv[1]
fs = open(fname, "r")

stline = int(input("Enter starting line : "))
endline = int(input("Enter ending line : "))

L = fs.readlines()

print("File:", fs.name)
print("Lines from", stline, "to", endline)
for Line in L[(stline-1):endline]:
print(Line)

fs.close()

File Handling 5: Display nth line of a file

# Display nth line of a file
# Use command line arguments

import sys

fname = sys.argv[1]
fs = open(fname, "r")

Nline = int(input("Enter line to print : "))

L = fs.readlines()

print("File:", fs.name)
print("Line number -", Nline)
print(L[Nline-1])

fs.close()

File Handling 4: Display first n lines of a file

# Display first n lines of a file
# Use command line arguments

import sys

fname = sys.argv[1]
fs = open(fname, "r")

L = fs.readlines()

Nlines = int(input("Enter number of lines to print : "))

print("First", Nlines, "of File:", fs.name)
for Line in L[0:Nlines]:
print(Line)

fs.close()

File Handling 3: Display file content with line number

# Display file content with line number
# Use command line arguments

import sys

fname = sys.argv[1]

fs = open(fname, "r")
Line_num = 1

print("File:", fs.name)

while(True):
Line = fs.readline()

if not Line:
break

print(Line_num, Line)
Line_num += 1

fs.close()


# Display file content with line number
# Use command line arguments

import sys

fname = sys.argv[1]
fs = open(fname, "r")

print("File:", fs.name)

L = fs.readlines()
for Line in L:
print(L.index(Line)+1, Line)

fs.close()

File Handling 2: Read from file and display

# Read from console and write to file
# Use command line arguments

import sys

fname = sys.argv[1]
fs = open(fname, "r")

print("File:", fs.name)

while(True):
Line = fs.readline()

if not Line:
break

print(Line)

fs.close()


# Read from console and write to file
# Use command line arguments

import sys

fname = sys.argv[1]
fs = open(fname, "r")

print("File:", fs.name)

L = fs.readlines()
 
for Line in L:
  print(Line)

fs.close()

File handling 1: Read from console and write to file

# Read from console and write to file
# Use command line arguments

import sys

fname = sys.argv[1]
fs = open(fname, "w")

print("Enter text. (Enter 'Stop' to quit)")
while(True):
Line = input()

if(Line=='Stop'):
break

fs.write(Line+'\n')

fs.close()

Pascal triangle

# Pascal triangle - 5 lines

L = [[1],[1,1]]
lno = 2

while(lno < 5):
tmp = [1]
i = 1
while(i<lno):
ele = L[lno-1][i-1]+L[lno-1][i]
tmp.append(ele)
i+=1
tmp.append(1)
lno+=1
L.append(tmp)


for ele in L:
print(" "*lno, end=" ")
for e in ele:
print(e, end= " ")
lno-=1
print()

Operators in Python



Operators in Python
Expressions in any programming language are a combination of operators and operands. Operators represent a computation and operands are the values or variables on which the computation is performed. When expressions are evaluated the result can be a numeric value or a Boolean value. The types of operators supported in Python are

1.    Arithmetic operators
2.    Assignment operators
3.    Relational operators
4.    Logical operators
5.    Membership operators
6.    Identity operators


Arithmetic operators:
Arithmetic operators are used for performing arithmetic operations. Various arithmetic operators are

Operator
Description
Example
Output
+
Addition
3 + 5
8
Subtraction
7 – 3
4
*
Multiplication
2 * 4
8
/
Division
9 / 3
3.0
%
Modulus (reminder operator)
5 % 2
1
//
Truncation (Floor) division
10 // 3
10 // 3.0
10.0 // 3
3
3.0
3.0
**
Exponentiation
2**3
8


Assignment operator
Assignment operator (=) is used to assign values to operands. The right side of the assignment operator may be a value or an expression. The output of the expression evaluation is assigned to the operand in the left side of the assignment operator. Example
a = 5                 (Direct assignment)
b = 3 + 4           (Evaluate expression containing values)
c = a * b           (Evaluate expression containing operands)
d = c + 1           (Evaluate expression containing values and operands)

Arithmetic Assignment operators are also called as shortcut operators. When an operator is used in the expression and the resultant value is assigned to the same operator it is called as arithmetic assignment operator. Example, consider
a += b                         is equal to                   a = a + b.
The value of a and b are added and the result is assigned to a. The old value of a is now replaced by the new value 8
           
Operator
Description
Example
Equivalent
+=
Addition assignment
a += b
a = a + b
–=
Subtraction assignment
a –= b
a = a – b
*=
Multiplication assignment
a *= b
a = a * b
/=
Division assignment
a /= b
a = a / b
%=
Modulus assignment
a %= b
a = a % b
//=
Truncation division assignment
a //= b
a = a // b
**=
Exponentiation assignment
a **= b
a = a ** b


Relational operators
Relational operators are also known as comparison operators and they return a Boolean value. They are used in conditional statements to compare values and take action depending on the result. If a = 5, b = 7 and c = 5

Operator
Description
Example
Result
==
Equal to
a == b
False
Less than
a < b
True
<=
Less than or Equal to
a <= b
True
Greater than
a > c
False
>=
Greater than or Equal to
a >= c
True
!=
Not equal to
a != b
True
<> 
Similar to (!=)
a <> b
True




Logical operators
Logical operators are based on Boolean Algebra and they return a Boolean value. They are used in situations involving more than one conditional statement.
Operator
Description
Evaluation
and
AND
Returns True if ALL conditional statements returns True. Else returns False
or
OR
Returns True if atleast one of the conditional statements return True. Else returns False
not
Unary NOT
Returns True if the operand has zero value. Else returns False

Example if a = 5, b = 3 and c = 7
          ((a > b) and (a > c)) will return False
((a > b) or (a > c)) will return True

Membership operators
Membership operators checks whether an element is a member of a sequence or not. The sequence can be List, String, Tuple or Dictionary. Example If List1 = [2, 4, 6, 8]

Operator
Example
Result
in
2 in List1
3 in List1
True
False
not in
2 not in List1
3 not in List1
False
True

Identity operators
Identity operators are used to compare the memory locations of two Python objects. Returns true if the two variables on either side of is operator are referring to the same object. Else returns False. Example if
List1 = [2, 4, 6, 8]
List2 = List1
Operator
Example
Result
is
List1 is List2
True
is not
List1 is not List2
False


Order of operations (Operator precedence)
When more than one operator appears in the expression, the order of evaluation depends on the precedence of operators. For mathematical operators Python follows the PEMDAS rule
1.    Parenthesis has the highest precedence.
a.    Example (1+1)*5 = 10 and not 6
2.    Exponentiation has the next highest precedence
a.    Example 2**3+1 = 9 and not 16
3.    Multiplication and Division have higher precedence than Addition and Subtraction.
a.    Note: Multiplication and Division have equal precedence. Similarly Addition and Subtraction have the equal precedence.
b.    Example:
                                                 i.    2*6/4 = 3                             (equal precedence for * and /)
                                               ii.    2+4-3 = 3                             (equal precedence for + and -)
                                              iii.    2*6+4 = 16 and not 20          (higher precedence for * than +)
4.    When operators have equal precedence the expression is evaluated from left to right.