I NEED TASK 3 ONLY
TASK 1
country.py
class Country:
def __init__(self, name, pop, area, continent):
self.name = name
self.pop = pop
self.area = area
self.continent = continent
def getName(self):
return self.name
def getPopulation(self):
return self.pop
def getArea(self):
return self.area
def getContinent(self):
return self.continent
def setPopulation(self, pop):
self.pop = pop
def setArea(self, area):
self.area = area
def setContinent(self, continent):
self.continent = continent
def __repr__(self):
return (f'{self.name} (pop:{self.pop}, size: {self.area}) in {self.continent} ')
TASK 2
Python Program:
File: catalogue.py
from Country import Country
class CountryCatalogue:
def __init__(self, countryFile):
""" Constructor that creates the
Country List using file """
# List that holds country
info
self.countryCat = []
# Opening file
fp = open(countryFile, "r")
# ignoring first line
header = fp.readline()
# Iterating over file
for line in fp:
# Stripping new
line
line =
line.strip()
# Splitting on
|
data =
line.split('|')
# Creating
country object
cObj =
Country(data[0], data[2], data[3], data[1])
# Adding to
list
self.countryCat.append(cObj)
# Closing file
fp.close()
def setPopulationOfCountry(self, country,
population):
""" Setter Methods """
# Iterating over Countries
for i in
range(len(self.countryCat)):
if
self.countryCat[i].getName() == country.getName():
# Updating values
self.countryCat[i].setPopulation(population)
print("\nUpdated Successfully...\n")
def setAreaOfCountry(self, country, area):
""" Setter Methods """
# Iterating over Countries
for i in
range(len(self.countryCat)):
if
self.countryCat[i].getName() == country.getName():
# Updating values
self.countryCat[i].setArea(area)
print("\nUpdated Successfully...\n")
def setContinentOfCountry(self, country,
continent):
""" Setter Methods """
# Iterating over Countries
for i in
range(len(self.countryCat)):
if
self.countryCat[i].getName() == country.getName():
# Updating values
self.countryCat[i].setContinent(continent)
print("\nUpdated Successfully...\n")
def findCountry(self,country):
""" Finds a country """
# Iterating over Countries
for cObj in self.countryCat:
if
cObj.getName() == country.getName():
return country
return None
def
addCountry(self,countryName,pop,area,cont):
""" Adds a country """
found = False
# Iterating over Countries
for i in
range(len(self.countryCat)):
if
self.countryCat[i].getName() == countryName:
found = True
if found:
return
False
else:
# Adding
country
cObj =
Country(countryName, pop, area, cont)
self.countryCat.append(cObj)
return
True
def printCountryCatalogue(self):
""" Prints country Catalogue
"""
for cObj in self.countryCat:
print(repr(cObj)
def saveCountryCatalogue(self,fname):
""" Saves information to file
"""
# Sorting the list
for i in
range(len(self.countryCat)):
for j in
range(i):
if self.countryCat[i].getName() <
self.countryCat[j].getName():
temp =
self.countryCat[i]
self.countryCat[i] =
self.countryCat[j]
self.countryCat[j] =
temp;
# Opening & Writing to
file
fp = open(fname, "w")
fp.write("Country|Continent|Population|Area\n")
# Iterating over objects
for cObj in self.countryCat:
fp.write(cObj.getName() + "|" + cObj.getContinent() + "|" +
cObj.getPopulation() + "|" + cObj.getArea() + "\n")
# Closing file
fp.close();
File: CountryCatalogue.py
from catalogue import CountryCatalogue
from Country import Country
def main():
""" Main function """
# Creating object
ccObj =
CountryCatalogue("d:\\Python\\countries.txt")
print("Data in file: \n")
# Printing values
ccObj.printCountryCatalogue()
# Adding country
ccObj.addCountry("DEF", "234,658,99", "56,859",
"Africa")
print("\n\nAfter adding new country: \n")
# Printing values
ccObj.printCountryCatalogue()
# Saving to file
ccObj.saveCountryCatalogue("d:\\Python\\newcountries.txt")
# Calling main
main()
______
TASK 3
Implement a Python module, called processUpdates.py, that has a
function
processUpdates(cntryFileName,updateFileName). This function takes
two parameters: the first
parameter will be the name of a file containing country data (e.g.
data.txt). The second file will
contain the name of a file containing updates. Each record in the
update file specifies updates for a
single country. The format of a record is as follows:
Country;update1;update2;update3
Where an “update” is of the form “L=value” and L can be P, for
population, A for area and C for
continent. Updates are separated by semicolons and a line can have
0, 1, 2 or 3 updates; any updates
beyond 3 are simply ignored.
An example of an update file is:
Brazil;P=193,364,111;A=8,511,966
Indonesia;P=260,581,345
Japan;P=127,380,555;A=377,800
Sweden;P=9,995,345;A=450,295;C=Europe
Italy; P=59,801,999
Canada;C=North America
Egypt;A=1,000,000 ; P=93,384,001
Notice that:
The updates can be in different orders, e.g. the updates for
Egypt are area first, then
population.
If a country is specified and that country is NOT already in the
catalogue then that country
and its attributes (at least the ones specified; not all have to be
specified) should be
added to the catalogue.
There can be spaces around the semicolons; spaces in other places
may cause errors and
should be handled as exceptions (see below).
The function processUpdates gets two files as parameters. The first
parameter is the name of the file
with the country data and the second parameter is the name of file
with the update data.
The country file should be processed first. The function
processUpdates should ensure that it exists.
If it does exist, it should then proceed to process the data file
using the class CountryCatalogue. If the
country file does not exist, then processUpdates should give the
user the option to quit or not
(prompts for “Y” (yes) or “N” (no)). If the user does not wish to
quite (responds with “N”), then the
function should prompt the user for the name of a new file. If the
user wishes to quit (responds with
a “Y” or anything other than a “N”, then the method should exit and
return False. The method should
continue to prompt for file names until a valid file is found or
the user quits.
If the user chooses to quit, i.e. no country file is processed,
then the function processUpdates should
NOT try to process the updates file, write to the file “output.txt”
the message "Update
Unsuccessful\n" – just the single line. It should then exit (i.e.,)
and return False.
If the function processUpdates has successfully processed the
country file, then it should proceed to
process the file of updates. It should prompt the user in a similar
manner to how the country file was
input, i.e., using a loop to continuously prompt the user until a
file was found that existed or until the
user quits.
If the user quits without an update file being selected, then the
function processUpdates should write
to the file “output.txt” the message "Update Unsuccessful\n" – just
the single line. It should then
exit (i.e.,) and return False.
If an update file is found, then the function processUpdates should
process the updates, i.e., update
the information about the countries and then output the new updated
list of countries in alphabetical
order to the file “output.txt”. The output should use the method
saveCountryCatalogue(self,fname)
from the class CountryCatalogue (see Task 2). It should then exit
and return True.
In processing the updates from the update file, the lines may have
extra spaces, forgotten semicolons,
etc. Some of these MAY cause exceptions when processing the line –
you program should be design
to catch any of these as exception. , e.g. bad values, incorrect
format, etc.
The main.py file is provided as the interface to your program. It
has been designed to prompt for the
names of a country file and a file of updates and then call the
function processUpdates; make sure
that you use these names of functions and methods as described
above. You may use the main.py
to test your program in other ways. Two additional data sets of
countries have been provided,
data2.txt and data3.txt, as well as two different files of updates,
upd2.txt and upd3.txt. You may use
these to test your program. NOTE: while main.py will test some
aspects of your program it does not
do a complete and thorough testing – this is left up to you. The TA
will use a program similar to,
but different than, main.py to grade your assignment ‐ it will
include other tests.
The following may be helpful in sorting data structures
http://pythoncentral.io/how‐to‐sort‐a‐list‐tuple‐or‐object‐with‐sorted‐in‐python/
http://pythoncentral.io/how‐to‐sort‐python‐dictionaries‐by‐key‐or‐value/
Non‐functional Specifications:
1. Include brief comments in your code identifying yourself,
describing the program, and describing
key portions of the code.
2. Use Python coding conventions and good programming techniques,
for example:
i. Meaningful variable names
ii. Conventions for naming variables and constants
iii. Readability: indentation, white space, consistency
Submit the files in which your classes and functions are
defined:
country.py containing the class Country;
catalogue.py containing the class CountryCatalogue;
processUpdates.py contain the function processUpdates.
Make sure you attach your python file to your assignment; DO NOT
put the code inline in the textbox.
Python Code:
File: processUpdates.py
from catalogue import CountryCatalogue
from Country import Country
def processUpdates(cntryFileName,updateFileName):
""" Processing updates """
# Opening country file
fp = open(cntryFileName, "r")
ofp = open("d:\\Python\\output.txt", "w")
# Checking status
if fp == None:
# Loop till user want to stop
processing
while True:
# Prompting
user
ch = input("Do
you want to Quit? 'Y' (yes) or 'N' (no): ")
# Checking
values
if ch.lower() ==
"y":
fName = input("Enter country file name: ")
# Checking status
fp = open(cntryFileName, "r")
if fp != None:
break
elif ch.lower()
== "N":
ofp.write("Update Unsuccessful\n")
ofp.close()
return
# Processing file
# Creating object
ccObj = CountryCatalogue(cntryFileName)
# Processing update file
ufp = open(updateFileName,"r")
for line in ufp:
# Stripping new lines
line = line.strip()
# Splitting on semicolon
data = line.split(';')
# Creating country object
cObj = Country(data[0], '', '',
'')
# Finding country for
existence
obj = ccObj.findCountry(cObj)
if obj == None:
# Fetching
values
for val in
data[1:]:
# Stripping spaces
val = val.strip()
# Checking type of update
if val[0] == 'P':
cObj.setPopulation(val[2:])
elif val[0] == 'A':
cObj.setArea(val[2:])
elif val[0] == 'C':
cObj.setContinent(val[2:])
# Adding to
catalogue
ccObj.addCountry(cObj.getName(), cObj.getPopulation(),
cObj.getArea(), cObj.getContinent())
else:
# Updating
values
for val in
data[1:]:
# Stripping spaces
val = val.strip()
# Checking type of update
if val[0] == 'P':
ccObj.setPopulationOfCountry(cObj, val[2:])
elif val[0] == 'A':
ccObj.setAreaOfCountry(cObj,
val[2:])
elif val[0] == 'C':
ccObj.setContinentOfCountry(cObj, val[2:])
# Closing file
fp.close()
# Printing values
ccObj.printCountryCatalogue()
# Saving to file
ccObj.saveCountryCatalogue("d:\\Python\\output.txt")
File: CountryCatalogue.py
from catalogue import CountryCatalogue
from Country import Country
from processUpdates import processUpdates
def main():
""" Main function """
# Processing updates
processUpdates("d:\\Python\\countries.txt",
"d:\\Python\\updates.txt")
# Calling main
main()
_____________________________________________________________________________________________________
Screenshot:
_____________________________________________________________________________________________________
Sample Run:
Get Answers For Free
Most questions answered within 1 hours.