Question

WordFrequencies.java 1. Prepare a text file that contains text to analyze. It could be song lyrics...

WordFrequencies.java

1. Prepare a text file that contains text to analyze. It could be song lyrics to your favorite song.

2. With your code, you’ll read from the text file and capture the data into a data structure.

3. Using a data structure, write the code to count the appearance of each unique word in the lyrics.

4. Print out a word frequency list.

Example output of the word frequency list:

100: frog

94: dog

43: cog

20: bog

use bufferreader and comment the code

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Program:

Output:

Sample Input File contents:

Code for the above screenshot:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Solution {
public static void main(String []args){
Scanner s = new Scanner(System.in);
//System.out.print("Enter a filename: "); //To make it dynamic by user input file name
String fileName = "input.txt"; //s.nextLine();
  
//Use the below code to find the current directory u are in which will make it easy for your to locate the Student file to run.
//System.out.println(System.getProperty("user.dir"));   
  
countWords(System.getProperty("user.dir"),fileName);
}
  
public static void countWords(String directory, String fileName) {
// Declare the HashMap
HashMap<String, Integer> wordCount = new HashMap();

// Puts together the string that the FileReader will refer to.
String fileNameWithDirectory = directory+ "\\src\\" + fileName;

try {
FileReader reader = new FileReader(fileNameWithDirectory);
BufferedReader br = new BufferedReader(reader);
// The BufferedReader reads the lines
  
String strCurrentLine;
while ((strCurrentLine = br.readLine()) != null) {
// First removes all non-letter characters, then to lowercase, then splits the input,
// \\s+ - matches sequence of one or more whitespace characters.
String[] words = strCurrentLine.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
int freq = 0;

// for loop goes through every word
for (int i = 0; i < words.length; i++) {
// Case if the HashMap already contains the key.
// If so, just increments the value

if (wordCount.containsKey(words[i])) {
int n = wordCount.get(words[i]);
wordCount.put(words[i], ++n);
}
// Otherwise, puts the word into the HashMap
else {
wordCount.put(words[i], 1);
}
}
}
  
for (Map.Entry entry : wordCount.entrySet())
System.out.println(entry.getValue() + ": " + entry.getKey());
  
// Catching the file not found error
// and any other errors
}
catch (FileNotFoundException e) {
System.err.println("File not found.");
}
catch (NullPointerException e) {
System.err.println("File is empty.");
}
catch (Exception e) {
System.err.print(e);
}
}
}

Add a comment
Know the answer?
Add Answer to:
WordFrequencies.java 1. Prepare a text file that contains text to analyze. It could be song lyrics...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • WordFrequencies.java 1. Prepare a text file that contains text to analyze. It could be song lyrics...

    WordFrequencies.java 1. Prepare a text file that contains text to analyze. It could be song lyrics to your favorite song. 2. With your code, you’ll read from the text file and capture the data into a data structure. 3. Using a data structure, write the code to count the appearance of each unique word in the lyrics. 4. Print out a word frequency list. Example output of the word frequency list: 100: frog 94: dog 43: cog 20: bog

  • Assignment 3: Word Frequencies Prepare a text file that contains text to analyze. It could be...

    Assignment 3: Word Frequencies Prepare a text file that contains text to analyze. It could be song lyrics to your favorite song. With your code, you’ll read from the text file and capture the data into a data structure. Using a data structure, write the code to count the appearance of each unique word in the lyrics. Print out a word frequency list. Example of the word frequency list: 100: frog 94: dog 43: cog 20: bog Advice: You can...

  • In python Count the frequency of each word in a text file. Let the user choose...

    In python Count the frequency of each word in a text file. Let the user choose a filename to read. 1. The program will count the frequency with which each word appears in the text. 2. Words which are the spelled the same but differ by case will be combined. 3. Punctuation should be removed 4. If the file does not exist, use a ‘try-execption’ block to handle the error 5. Output will list the words alphabetically, with the word...

  • Use the csv file on spotify from any date Code from lab2 import java.io.File; import java.io.FileNotFoundException;...

    Use the csv file on spotify from any date Code from lab2 import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class SongsReport {    public static void main(String[] args) {               //loading name of file        File file = new File("songs.csv"); //reading data from this file        //scanner to read java file        Scanner reader;        //line to get current line from the file        String line="";       ...

  • CSC110 Lab 6 (ALL CODING IN JAVA) Problem: A text file contains a paragraph. You are to read the contents of the file, store the UNIQUEwords and count the occurrences of each unique word. When the fil...

    CSC110 Lab 6 (ALL CODING IN JAVA) Problem: A text file contains a paragraph. You are to read the contents of the file, store the UNIQUEwords and count the occurrences of each unique word. When the file is completely read, write the words and the number of occurrences to a text file. The output should be the words in ALPHABETICAL order along with the number of times they occur and the number of syllables. Then write the following statistics to...

  • I need help in C++ implementing binary search tree. I have the .h file for the...

    I need help in C++ implementing binary search tree. I have the .h file for the binary search tree class. I have 4 classic texts, and 2 different dictionaries. Classic Texts: Alice In Wonderland.txt A Tale of Two Cities.txt Pride And Prejudice.txt War and Peace.txt 2 different dictionaries: Dictionary.txt Dictionary-brit.txt The data structures from the standard template library can not be used.The main program should open the text file, read in the words, remove the punctuation and change all the...

  • In this assignment, you will explore more on text analysis and an elementary version of sentiment...

    In this assignment, you will explore more on text analysis and an elementary version of sentiment analysis. Sentiment analysis is the process of using a computer program to identify and categorise opinions in a piece of text in order to determine the writer’s attitude towards a particular topic (e.g., news, product, service etc.). The sentiment can be expressed as positive, negative or neutral. Create a Python file called a5.py that will perform text analysis on some text files. You can...

  • In this assignment you’ll implement a data structure called a trie, which is used to answer...

    In this assignment you’ll implement a data structure called a trie, which is used to answer queries regarding the characteristics of a text file (e.g., frequency of a given word). This write-up introduces the concept of a trie, specifies the API you’re expected to implement, and outlines submission instructions as well as the grading rubric. Please carefully read the entire write-up before you begin coding your submission. Tries A trie is an example of a tree data structure that compactly...

  • Recursion and Trees Application – Building a Word Index Make sure you have read and understood...

    Recursion and Trees Application – Building a Word Index Make sure you have read and understood ·         lesson modules week 10 and 11 ·         chapters 9 and 10 of our text ·         module - Lab Homework Requirements before submitting this assignment. Hand in only one program, please. Background: In many applications, the composition of a collection of data items changes over time. Not only are new data items added and existing ones removed, but data items may be duplicated. A list data structure...

  • SCREENSHOTS OF CODE ONLY!! PLEASE DON'T POST TEXT!! C++ CODE! PLEASE DON'T REPOST OLD POSTS! Objective...

    SCREENSHOTS OF CODE ONLY!! PLEASE DON'T POST TEXT!! C++ CODE! PLEASE DON'T REPOST OLD POSTS! Objective To gain experience with the operations involving binary search trees. This data structure as linked list uses dynamic memory allocation to grow as the size of the data set grows. Unlike linked lists, a binary search tree is very fast to insert, delete and search. Project Description When an author produce an index for his or her book, the first step in this process...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT