Question

Project File Processing. Write a program that will read in from input file one line at...

Project File Processing.

Write a program that will read in from input file one line at a time until end of file and output the number of words in the line and the number of occurrences of each letter. Define a word to be any string of letters that is delimited at each end by either whitespace, a period, a comma or the beginning or end of the line. You can assume that the input consists entirely of letters, whitespaces, commas and periods. When outputting the number of letters that occur in a line, be sure to count upper and lowercase versions of a letter as the same letter. Output the letters in alphabetical order and list only those letters that do occur in the input line. For example, the input line:-I say HI should produce output similar to the following:-

3 words

1 a

1 h

2 i

1 s

1 y

Note: in addition to the above, output the result to file named “result.txt”

Homework Answers

Answer #1

JAVA PROGRAM

import java.io.BufferedReader;

import java.io.FileReader;

import java.util.Arrays;

import java.io.File;

import java.io.FileWriter;

import java.io.BufferedWriter;

public class WordLetterCount {

    public static void main(String[] args) {

    // Array of occurence counts

    int countArray[]  = new int[26];

    // Initializing the array with 0's

    Arrays.fill(countArray, 0);

    try {

        // Opening file to read

        BufferedReader br = new BufferedReader(new FileReader("testFile.txt"));

        String line = "";

        FileWriter fw=new FileWriter("results.txt");    

        // Iterating loop till the end of the file

        while((line = br.readLine())!=null) {

            // Splitting lines using whitespace/commas/period as delimiter

            String words[] = line.split("[\\s,.]+");

            // Iterating for each word in the array

            for(int i=0;i<words.length;i++) {

                // Iterating for each letter in each word

                for(int j = 0;j<words[i].length();j++) {

                    // ch : current character in lower case

                    char ch = Character.toLowerCase(words[i].charAt(j));

                    // index : ASCII value of character ch

                    int asciiValue =  (int)ch;

                    //Incrementing occurence count

                    countArray[asciiValue-97]+=1;

                }

            }   

            

            fw.write(words.length+ " words\n");

            // Print number of words in current line

            System.out.println(words.length+ " words");

            // Iterate over countArray and check if value at index i is not 0, means the character was not present in line

            // If yes, print count and corresponding alphabet

            for(int i =0 ;i<26;i++) {

                if(countArray[i]!=0) {

                    System.out.println(countArray[i] +" "+(char)(i+97));

                    fw.write(countArray[i] +" "+(char)(i+97)+"\n");

                }

            }

            System.out.println();

            fw.write("\n");


            // Reset the array to all 0,

            // for keeping count of character of next line

            Arrays.fill(countArray, 0);

        }

        br.close();

        fw.close();

    } catch(Exception e) {

    System.out.println("File doesn't exits!!");

    }

}

}

PROGRAM SCREENSHOT

INPUT FILE: testFile.txt

OUTPUT FILE : results.txt

Note:

# The alphabet occurance is counted using ASCII values. An array of size 26 is made corresponding to each alphabet. Now

asciiValue-97 in array corresponds to the exact alphabet in the count array.

This is done because ASCII value for a-b is 97-122

So , for ch = a, asciiValue = 97

So, countArray[asciiValue-97] = countArray[0], which represents count of character a at position 0

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
I need python code for this. Write a program that inputs a text file. The program...
I need python code for this. Write a program that inputs a text file. The program should print the unique words in the file in alphabetical order. Uppercase words should take precedence over lowercase words. For example, 'Z' comes before 'a'. The input file can contain one or more sentences, or be a multiline list of words. An example input file is shown below: example.txt the quick brown fox jumps over the lazy dog An example of the program's output...
Please write a program that reads the file you specify and calculates how many times each...
Please write a program that reads the file you specify and calculates how many times each word stored in the file appears. However, ignore non-alphabetic words and convert uppercase letters to lowercase letters. For example, all's, Alls, alls are considered to be the same words. What is the output of the Python program when the input file is specified as "proverbs.txt"? That is, in your answer, include the source codes of your word counter program and its output. <proverbs.txt> All's...
C++ create a program that: in main: -opens the file provided for input (this file is...
C++ create a program that: in main: -opens the file provided for input (this file is titled 'Lab_HW10_Input.txt' and simply has 1-10, with each number on a new line for 10 lines total) -calls a function to determine how many lines are in the file -creates an array of the proper size -calls a function to read the file and populate the array -calls a function to write out the contents of the array in reverse order *output file should...
You are to write a C program that will read from a file, one or more...
You are to write a C program that will read from a file, one or more sets of x,y coordinates. Each set of coordinates is part of a Cartesian system. A Cartesian coordinate system is a system that specifies each point uniquely in a plane by a pair of numerical coordinates. Your program will determine which quadrant each set belong. - Quadrants are often numbered 1st - 4th and denoted by Roman numerals: I(+,+), II (−,+), III (−,−), and IV...
C Program Write a program to count the frequency of each alphabet letter (A-Z a-z, total...
C Program Write a program to count the frequency of each alphabet letter (A-Z a-z, total 52 case sensitive) and five special characters (‘.’, ‘,’, ‘:’, ‘;’ and ‘!’) in all the .txt files under a given directory. The program should include a header count.h, alphabetcount.c to count the frequency of alphabet letters; and specialcharcount.c to count the frequency of special characters. Please only add code to where it says //ADDCODEHERE and keep function names the same. I have also...
I can open the file in the program, but I cannot figure out how to properly...
I can open the file in the program, but I cannot figure out how to properly split the data and assign a grade to the number values in the text file. I keep getting :: ValueError: invalid literal for int() with base 10: 'Roger Jones 75\n' Below are the assignment details: This program processes grades for a small class. It reads an input file named grade_input.txt where each record contains a student’s first name, last name and numeric grade (a...
Python Programming Build a python programming that asks the user for a three-letter substring. The program...
Python Programming Build a python programming that asks the user for a three-letter substring. The program should then proceed to read the file strings.txt. Each line in strings.txt will contain a string. Your program should then test to see how many non-overlapping occurrences of the three-letter substring occur in that string and test whether the string is a palindrome. The program should then proceed to create an output file string_stats.txt, which contains the original data on one line and the...
C++ Programming   You are to develop a program to read Baseball player statistics from an input...
C++ Programming   You are to develop a program to read Baseball player statistics from an input file. Each player should bestored in a Player object. Therefore, you need to define the Player class. Each player will have a firstname, last name, a position (strings) and a batting average (floating point number). Your class needs to provide all the methods needed to read, write, initialize the object. Your data needs to be stored in an array of player objects. The maximum...
Write a Java program that Reads baseball data in from a comma delimited file. Each line...
Write a Java program that Reads baseball data in from a comma delimited file. Each line of the file contains a name followed by a list of symbols indicating the result of each at bat: 1 for single, 2 for double, 3 for triple, 4 for home run, o for out, w for walk, s for sacrifice Statistics are computed and printed for each player. EXTRA CREDIT (+10 points); compute each player's slugging percentage https://www.wikihow.com/Calculate-Slugging-Percentage Be sure to avoid a...
JAVA ASSIGNMENT 1. Write program that opens the file and process its contents. Each lines in...
JAVA ASSIGNMENT 1. Write program that opens the file and process its contents. Each lines in the file contains seven numbers,which are the sales number for one week. The numbers are separated by comma.The following line is an example from the file 2541.36,2965.88,1965.32,1845.23,7021.11,9652.74,1469.36. The program should display the following: . The total sales for each week . The average daily sales for each week . The total sales for all of the weeks .The average weekly sales .The week number...