Experiment no 7:
1. Write python function to count number of words in a file.
Program:
file = open("sample.txt", "rt")
data = file.read()
words = data.split()
print('Number of words in text file :', len(words))
output:
Number of words in text file : 8
2. Write python program to create a file F3 by copying one line each alternately from file1 and file 2.
Program 1:
with open('sample.txt') as fh1, open('second.txt') as fh2,
open('readme.txt', 'w') as f:
for line1, line2 in zip(fh1, fh2):
# line1 from abc.txt, line2 from test.txtg
print(line1+line2)
lines = [ line1+line2 ]
for line in lines:
f.write(line)
f.write('\n')
Program 2:
1 = open('p1.txt','r')
f2=open("p2.txt","r")
f3=open("p3.txt","w")
for x in range(1,100):
if(x%2!=0):
i=f1.readline()
else:
i = f2.readline()
f3.write(i)
f3.close()
f3=open("p3.txt","r")
print(f3.read())
f1.close()
f2.close()
f3.close()
P1.txt
aman
banana
cat
dog
elephant
p2.txt
zebra
yak
xerox
well
neha
p3.txt
aman
zebra
banana
yak
cat
xerox
dog
well
elephant
neha
______________________________________________________
# Python program to count the
# number of lines in a text file
# Opening a file
file = open("gfg.txt","r")
Counter = 0
# Reading from file
Content = file.read()
CoList = Content.split("\n")
for i in CoList:
if i:
Counter += 1
print("This is the number of lines in the file")
print(Counter)
Output:
This is the number of lines in the file
4
How To Read a File Line by Line using for Loop in Python?
We can read a file line-by-line using a for loop as shown as under:
for line in fie1:
print(line, end = ”)
Python Complete Program Example:
# write three lines in a file
file1 = open(“sample.txt”, “w”)
file1.write(“Line number1\nLine number 2\nLine number 3\n”)
file1.close()
# read all data with read method and display it
file1 = open(“sample.txt”, “r”)
for line in file1:
print(line, end=”)
Output:
Line number1
Line number 2
Line number 3
Experiment no 8:
Example 1
# using array-scalar
type import numpy as
np dt
=np.dtype(np.int32)
printdt
The output is as follows −
int32
Example 2
#int8, int16, int32, int64 can be replaced by equivalent string 'i1', 'i2','i4', etc. import
numpy as np
dt =np.dtype('i4')
printdt
The output is as follows −
int32
Example 3
# using endian
notation import
numpy as np dt
=np.dtype('>i4')
printdt
The output is as follows −
>i4
The following examples show the use of structured data type. Here, the field name and the
corresponding scalar data type is to be declared.
Example 4
# first create structured data
type import numpy as np dt
=np.dtype([('age',np.int8)])
printdt
The output is as follows −
[('age', 'i1')]
Example 5
# now apply it to ndarray object
import numpy as np
dt =np.dtype([('age',np.int8)]) a
=np.array([(10,),(20,),(30,)],dtype= dt)
print a
The output is as follows −
[(10,) (20,) (30,)]
Example 6
# file name can be used to access content of age column import
numpy as np
dt =np.dtype([('age',np.int8)]) a
=np.array([(10,),(20,),(30,)],dtype= dt)
print a['age']
The output is as follows −
[10 20 30]
Example 7
The following examples define a structured data type called student with a string field 'name', an
integer field 'age' and a float field 'marks'. This dtype is applied to ndarray object.
import numpy as np
student =np.dtype([('name','S20'),('age','i1'),('marks','f4')]) printstudent
The output is as follows −
[('name', 'S20'), ('age', 'i1'), ('marks', '<f4')])
Example 8 import
numpy as np
student =np.dtype([('name','S20'),('age','i1'),('marks','f4')])
a =np.array([('abc',21,50),('xyz',18,75)],dtype= student)
print a
The output is as follows −
[('abc', 21, 50.0), ('xyz', 18, 75.0)]
ndarray.shape
This array attribute returns a tuple consisting of array dimensions. It can also be used to resize the
array. Example 1 import numpy as np a =np.array([[1,2,3],[4,5,6]]) printa.shape
The output is as follows −
(2, 3)
Example 2
# this resizes the ndarray
import numpy as np
a
=np.array([[1,2,3],[4,5,6]])
a.shape=(3,2) print a
The output is as follows −
[[1,
2]
[3,
4]
[5, 6]]
Example 3
NumPy also provides a reshape function to resize an array.
import numpy as np a
=np.array([[1,2,3],[4,5,6]])
b =a.reshape(3,2) printb
The output is as follows −
[[1,
2]
[3,
4]
[5, 6]]
ndarray.ndim
This array attribute returns the number of array dimensions.
Example 1
# an array of evenly spaced numbers
import numpy as np a
=np.arange(24) print a
The output is as follows −
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
Example 2
# this is one dimensional
array import numpy as np a
=np.arange(24) a.ndim
# now reshape it
b
=a.reshape(2,4,3)
printb
# b is having three dimensions
The output is as follows −
[[[ 0, 1,
2] [ 3,
4, 5]
[ 6, 7, 8]
[ 9, 10, 11]]
[[12, 13, 14]
[15, 16, 17]
[18, 19, 20]
[21, 22, 23]]]
numpy.itemsize
This array attribute returns the length of each element of array in bytes.
Example 1
# dtype of array is int8 (1 byte)
import numpy as np x
=np.array([1,2,3,4,5],dtype= np.int8)
printx.itemsize The output is as
follows −
Example 2
# dtype of array is now float32 (4 bytes)
import numpy as np x
=np.array([1,2,3,4,5],dtype= np.float32)
printx.itemsize
The output is as follows −
Experiment no 9:
ARTISTIC TUTORIAL:
LEGEND GUIDE
Styling with cycler
MATPLOTLIB Advanced
SOURCE CODE:
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
verts = [
(0., 0.), # left, bottom
(0.5, 1.), # left, top
(1., 1.), # right, top
(0.5, 0.), # right, bottom
(0., 0.), # ignored
codes = [
Path.MOVETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.CLOSEPOLY,
path = Path(verts, codes)
fig, ax = plt.subplots()
patch = patches.PathPatch(path, facecolor='orange', lw=2)
ax.add_patch(patch)
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
plt.show()
Practical No.10
Program:-
1) def say_hello(recipient):
return 'Hello, {}!'.format(recipient) say_hello('Tim') -‘Hello’ Tim! 2) import
numpy as np def square(x): return x * x
3) x = np.random.randint(1, 10) y = square(x) print('%d squared is
%d' % (x, y))
-6 squared is 36
4)print('Is %d squared %d?' % (x, y)) -Is 6 squared 36?
5)print('Is %d squared %d?' % (x, y)) y = 10 print('Is %d squared is %d?' % (x, y)) - Is 6
squared 36?
Is 6 squared is 10? 6) %matplotlib inline import pandas as pd import matplotlib.pyplot as plt
import seaborn as sns sns.set(style="darkgrid") df = pd.read_csv('fortune500.csv') df.head()