Question

In: Computer Science

PYTHON. Tasks: Create and test the openFileReadRobust() function to open file (for reading) whose name is...

PYTHON.

Tasks:

  1. Create and test the openFileReadRobust() function to open file (for reading) whose name is provided from the standard input (keyboard) – the name is requested until it is correct
  2. Create and test the openFileWriteRobust () function to open file (for writing) whose name is provided from the standard input (keyboard) – the name is requested until is correct
  3. Extend the program to count number of characters, words and lines in a file as discussed in the classby including openFileReadRobust() and openFileWriteRobust () functions
  4. Create simple tallying program to input sequence of integers (each integer 0-100) from a file (name to be entered from the keyboard using openFileReadRobust() function), compute the tally sheet discarding all bad data. Display the discarded bad data on the screen.
  5. Write the content of the tally sheet (write only non-zero counts of numbers – numbers that are in the input file) to a standard output (the shell window).
  6. Extend the program to write the content of the tally sheet (write only non-zero counts of numbers – numbers that are in the input file) to a file (name to be entered from the keyboard). Display the content of the file on the screen.

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

Solutions

Expert Solution

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


Related Solutions

Please Use Python 3.The Problem: Read the name of a file and then open it for...
Please Use Python 3.The Problem: Read the name of a file and then open it for reading. Read the name of another file and then open it for output. When the program completes, the output file must contain the lines in the input file, but in the reverse order. • Write the input, output, and the relationship between the input and output. • Develop the test data (A single test will be alright). Make the input file at least 3...
Python - files: find a solution for each following: -Open the file hostdata.txt for reading. -Store...
Python - files: find a solution for each following: -Open the file hostdata.txt for reading. -Store four file objects corresponding to the files winter2003.txt , spring2003.txt, summer2003.txt, and fall2003.txt in the variables winter, spring, summer, and fall (respectively), and open them all for reading. -Write a statement to open the file yearsummary.txt in a way that erases any existing data in the file. -Use the file object output to write the string "3.14159" to a file called pi. -A file...
Write a Python program that uses function(s) for writing to and reading from a file: a....
Write a Python program that uses function(s) for writing to and reading from a file: a. Random Number File Writer Function Write a function that writes a series of random numbers to a file called "random.txt". Each random number should be in the range of 1 through 500. The function should take an argument that tells it how many random numbers to write to the file. b. Random Number File Reader Function Write another function that reads the random numbers...
Create a Word file containing the following: The full name of the “test subject” The test...
Create a Word file containing the following: The full name of the “test subject” The test subject is a person, not yourself, who can say the names of the products. The best test subject is one who is adamant about being an expert who can distinguish brand A from B. You cannot be the test subject because you generate the sequence, and the test subject cannot see it for an unbiased test. Pets and babies are not allowed as they...
Language: Python Function name : sort_by_rating Parameters : file (.csv file), category (string), order (boolean) Returns:...
Language: Python Function name : sort_by_rating Parameters : file (.csv file), category (string), order (boolean) Returns: None Description : You want to see what order the items of a particular category in your file would be in if you sorted them by rating. Given a file, a category of clothing, and an order boolean (True for ascending order, False for descending order), create a function that writes a file called “sorted_items.csv” that includes all of the items in the specified...
Using Python create a script called create_notes_drs.py. In the file, define and call a function called...
Using Python create a script called create_notes_drs.py. In the file, define and call a function called main that does the following: Creates a directory called CyberSecurity-Notes in the current working directory Within the CyberSecurity-Notes directory, creates 24 sub-directories (sub-folders), called Week 1, Week 2, Week 3, and so on until up through Week 24 Within each week directory, create 3 sub-directories, called Day 1, Day 2, and Day 3 Bonus Challenge: Add a conditional statement to abort the script if...
Query the user for the name of a file. Open the file, read it, and count...
Query the user for the name of a file. Open the file, read it, and count and report the number of vowels found in the file. Using C++.
Write a function redact() takes as input a file name. See secret.txt for the initial test....
Write a function redact() takes as input a file name. See secret.txt for the initial test. The function should print the contents of the file on the screen with this modification: Every occurrence of string 'secret' in the file should be replaced with string 'xxxxxx'. Every occurrence of “agent’ should be replaced with ‘yyyyyy’. Every occurrence of carrier should be replaced with ‘zzzzzz’. This function should catch exceptions. FOR PYTHON
USING JAVASCRIPT Create a file name dayOfWeek.js and write an arrow function named dayOfWeek that accepts...
USING JAVASCRIPT Create a file name dayOfWeek.js and write an arrow function named dayOfWeek that accepts a Date object dateStr and returns a string that is the day of the week in English form (i.e. “Sunday”, “Monday”, etc.). Test your function by creating a date object that is a significant date to you (such as your birthday) and passing that date object to your function. Test your function at least twice with two different dates. Submit the dayOfWeek.js file to...
Python HW Open a new Jupyter notebook Create a new function named fibonacci() that takes one...
Python HW Open a new Jupyter notebook Create a new function named fibonacci() that takes one required parameter: maxint, an integer that will serve as the upper bound of the loop Following the example on the Python tutorial: https://docs.python.org/3/tutorial/introduction.html#first-steps-towards-programming Our implementation will have a few changes: While you will use a while loop to make a Fibonacci sequence, the upper bound of the sequence will be your maxint parameter. Store the results into a list and append each new generated...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT