In: Computer Science
PYTHON.
Tasks:
Assume the content of the file myData1.txt:
5
100
111
OK
55
5
55
5
The interaction of your program should be displayed in the Shell window similarly as shown below:
Task 1
What is the input file name?
myData.txt
This file cannot be opened
What is the input file name?
myData1.txt
Task 2
What is the output file name?
myResults1.txt
Task 3
The number of characters is: 15
The number of words is: 8
The number of lines is: 8
Task 4
Discarded bad data: 111, OK
Task 5
The tally sheet based on your input file is:
Number of 5’s: 3
Number of 55’s: 2
Number of 100’s: 1
Task 6
The tally sheet written to the file: myResults1.txt
Copy of the content of the file myResults1.txt is:
Number of 5’s: 3
Number of 55’s: 2
Number of 100’s: 1
from collections import Counter
import collections
#method to open read file
def openFileReadRobust():
#takinf user input
file_name = input('What is the input file name?\n');
try:
#will throw an exception if file not found
f = open(file_name, 'r')
#returning file name
return file_name
except:
print('This file cannot be opened')
openFileReadRobust()
#method for output file
def openFileWriteRobust():
file_name = input('What is the output file name?\n');
try:
#will throw an exception if file not found
f = open(file_name, 'w')
return file_name
except:
print('This file cannot be opened')
openFileWriteRobust()
#method countData
def countData(file):
data = file.readlines()
words = 0
charac = 0
#counting lines, words and characters from the file
for line in data:
s = line.strip()
words += (s.count(' ') + 1)
for char in s:
if char is not ' ':
charac += 1
print("The number of characters is:", charac)
print("The number of words is:", words)
print("The number of lines is:", len(data))
#method to chgeck the data and discard the data
def discardData(file):
data = file.readlines()
ans = []
disc = []
for line in data:
s = line.strip()
if s.isdigit():
a = int(s)
if a >= 0 and a <= 100:
ans.append(a)
else:
disc.append(s)
else:
disc.append(s)
print("Discarded bad data:", ", ".join(disc))
return sorted(ans)
#method to print the data
def printData(counter):
s = []
print('The tally sheet based on your input file is:')
for k, v in counter.items():
s.append('Number of '+ str(k)+ "'s: "+ str(v))
return s
def main():
print('Task 1')
inpFile = openFileReadRobust()
print('Task 2')
outFile = openFileWriteRobust()
print('Task 3')
countData(open(inpFile))
print('Task 4')
ans = discardData(open(inpFile))
print('Task 5')
count = dict(Counter(ans))
od = collections.OrderedDict(sorted(count.items()))
s = printData(od)
print("\n".join(s))
print('Task 6')
open(outFile, 'w').writelines(s)
print('Copy of the content of the file myResults1.txt is:')
print("\n".join(s))
main()
IF THERE IS ANYTHING THAT YOU DO NOT UNDERSTAND THEN PLEASE MENTION IT IN THE COMMENTS SECTION