# Written by Nishant Malik for course Math 50 Fall 2015 (Dartmouth College)
def read_tb_data(ch,pr):
import urllib2
import numpy as np
str1='https://netfiles.umn.edu/users/nacht001/www/nachtsheim/Kutner/Chapter%20%20'
# chapter number
if(ch<10):
ch_str=str(ch).zfill(2)
else:
ch_str=str(ch)
if(pr<10):
pr_str=str(pr).zfill(2)
else:
pr_str=str(pr)
str2=str(ch)+'%20Data%20Sets/CH'+ch_str+'PR'+pr_str+'.txt'
str3=str1+str2
try: urllib2.urlopen(str3)
except urllib2.URLError as e:
print(e.reason), '\nChapter number or problem number is wrong. Try again!'
return np.array([])
flink = urllib2.urlopen(str3)
data=[]
for line in flink:
lines=line.strip('\r\n'); lines=lines.split();
data.append(lines)
flink.close()
colnos=len(data[0])
j=0; xdata = np.zeros((len(data),colnos))
for line in data:
for k in range(0,colnos):
xdata[j,k]=data[j][k]
j=j+1
return xdata
This function can also be saved in a separte file in your working directory, with a file name. For example lets save it as read_data_fx. It can be imported as shown below.
# import the above described function if saved in file named "read_data_fx"
from read_data_fx import read_tb_data
A wrong chapter number or problem number will raise a error (exception). For example:
#There is no data for problem 10 in chapeter 2
data=read_tb_data(2,10)
# There is data for problem 20 in chapter 1
data=read_tb_data(1,20)
# we can see what is inside data as follows
#no. of rows and columns in the data
rown,coln=data.shape
print 'numbers of columns =',coln, 'numbers of rows=', rown
print 'First column of the data =', data[:,0]
print 'Second column of the data =', data[:,1]
def read_tb_dataTA(ch,pr):
import urllib2
import numpy as np
str1='https://netfiles.umn.edu/users/nacht001/www/nachtsheim/Kutner/Chapter%20%20'
# chapter number
if(ch<10):
ch_str=str(ch).zfill(2)
else:
ch_str=str(ch)
if(pr<10):
pr_str=str(pr).zfill(2)
else:
pr_str=str(pr)
str2=str(ch)+'%20Data%20Sets/CH'+ch_str+'TA'+pr_str+'.txt'
str3=str1+str2
try: urllib2.urlopen(str3)
except urllib2.URLError as e:
print(e.reason), '\nChapter number or example number is wrong. Try again!'
return np.array([])
flink = urllib2.urlopen(str3)
data=[]
for line in flink:
lines=line.strip('\r\n'); lines=lines.split();
data.append(lines)
flink.close()
colnos=len(data[0])
j=0; xdata = np.zeros((len(data),colnos))
for line in data:
for k in range(0,colnos):
xdata[j,k]=data[j][k]
j=j+1
return xdata
Again one can save this function in the same file read_data_fx and can import it as follows:
from read_data_fx import read_tb_dataTA
data=read_tb_dataTA(3,4)
print data