Question

Java A bigram is a pair of adjacent words in a sequence. Bigrams overlap so that...

Java

A bigram is a pair of adjacent words in a sequence. Bigrams overlap so that in the sequence "a b. c d", the bigrams are ("a", "b."), ("b.", "c"), ("c", "d"). You will write a simple parser which builds a bigram model based on input text and will allow checking sentences and generating sequences. To do so, you should take advantage of Java’s collection classes including Maps.

Create a class called Bigram. The class will have a constructor which takes a String. A Bigram object’s job is to analyze this single String given to the constructor. You may want to use the constructor to preprocess the input to support the two methods below. Use a Scanner with its default tokenization on the String (don’t call useDelimeter). As long as hasNext() returns true, each call to next() on the Scanner will retrieve the next word. Note that some words will be capitalized differently or contain punctuation. Treat each of those differently (for example, "Dogs", "dogs", and "dogs." are all different strings).

public boolean check(String sentence) (Sentence checking method): Checking a sentence will consist of looking at each (overlapping) pair of adjacent words. If all adjacent pairs in the sentence were seen in your constructor text, your code will return true, otherwise false.

Example:

Bigram x = new Bigram("Bob likes dogs. Bill likes cats. Jane hates dogs.");


x.check("Bob likes cats.") returns true: "Bob likes" and "likes cats." both appear.

x.check("Jane likes cats.") returns false: "Jane likes" does not appear in the input text.

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

PROGRAM :

import java.util.*;

//class for Bigram

public class Bigram

{

//map for bigram counts

private Map<String,Map<String,Integer>> bigramCounts;

public Bigram(String s)

{

bigramCounts = new HashMap<String,Map<String,Integer>>();

Scanner sc = new Scanner(s);

String c, p = null;

while(sc.hasNext())

{

c = sc.next();

if(p != null)

{

if(bigramCounts.get(p) == null)

{

bigramCounts.put(p, new TreeMap<String,Integer>());

}

if(bigramCounts.get(p).get(c) == null)

{

bigramCounts.get(p).put(c,1);

}

else

{

int count = bigramCounts.get(p).get(c);

bigramCounts.get(p).put(c,count+1);

}

}

p = c;

}

}

//method for check() function

public boolean check(String s)

{

Scanner sc = new Scanner(s);

boolean possible = true;

String c, p = null;

while(sc.hasNext())

{

c = sc.next();

if(p != null)

{

if(bigramCounts.get(p) == null)

{

possible = false;

break;

}

if(bigramCounts.get(p).get(c) == null)

{

possible = false;

break;

}

}

p = c;

}

return possible;

}

//method for generate() function

public String[] generate(String start, int count)

{

String[] generateString = new String[count];

generateString[0] = start;

int i = 1;

while(i < count)

{

if(bigramCounts.get(generateString[i-1]) == null)

{

break;

}

//assign key set using Set

Set<String> ks = bigramCounts.get(generateString[i-1]).keySet();

//assign order list using List

List<String> orderList = new ArrayList<String>(ks);

Collections.reverse(orderList);

//assign maximum frequency is 0

int mfreq = 0;

//assign minimum word frequency

String mwFreq = null;

for(String str : orderList)

{

if(mfreq == 0)

{

mwFreq = str;

mfreq = bigramCounts.get(generateString[i-1]).get(str);

}

else if (bigramCounts.get(generateString[i-1]).get(str)==mfreq)

{

if(str.compareTo(mwFreq) < 0)

{

mwFreq = str;

}

}

else

{

break;

}

}

generateString[i++] = mwFreq;

}

return generateString;

}

//main function

public static void main(String []args)

{

Bigram x = new Bigram("Bob likes dogs. Bill likes cats. Jane hates dogs.");

//call check() method

System.out.println(x.check("Bob likes cats."));

System.out.println(x.check("Jane likes cats."));

Bigram y = new Bigram("The balloon was red. The balloon got bigger and bigger. The balloon popped.");

System.out.print("[");

//call generate method

for(String str: y.generate("The", 3))

{

System.out.print('"'+ str +'"'+" ");

}

System.out.print("]\n");

System.out.print("[");

for(String str:y.generate("popped.", 1))

{

System.out.print('"'+ str +'"'+" ");

}

System.out.print("]\n");

}

}

Add a comment
Know the answer?
Add Answer to:
Java A bigram is a pair of adjacent words in a sequence. Bigrams overlap so that...
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
  • Write a C++ program that will count the number of words and vowels in a sentence....

    Write a C++ program that will count the number of words and vowels in a sentence. Create a bool function called isVowel that accepts a character as a parameter and returns a true if it’s a vowel (aeiou) and false otherwise. Create an int function named countVowels that will accept a string variable as a parameter and will return the number of vowels in it. Call the isVowel function as part of this process. Write an int function named countWords...

  • In this lab you will write a spell check program. The program has two input files:...

    In this lab you will write a spell check program. The program has two input files: one is the dictionary (a list of valid words) and the other is the document to be spellchecked. The program will read in the words for the dictionary, then will read the document and check whether each word is found in the dictionary. If not, the user will be prompted to leave the word as is or type in a replacement word and add...

  • 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...

  • Please write a code in Java where it says your // your code here to run...

    Please write a code in Java where it says your // your code here to run the code smoothly. Import statements are not allowed. _ A Java method is a collection of statements that are grouped together to perform an operation. Some languages also call this operation a Function. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console. Please write the code according to functions assigned...

  • Please write a code in Java where it says your // your code here to run...

    Please write a code in Java where it says your // your code here to run the code smoothly. Import statements are not allowed for this assignment, so don't use them. _ A Java method is a collection of statements that are grouped together to perform an operation. Some languages also call this operation a Function. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console. Please...

  • in java no mathcall please ennas are out of date.Please sign was wkollieemail.cpeedu so we can...

    in java no mathcall please ennas are out of date.Please sign was wkollieemail.cpeedu so we can verily your subscription Sign In ASSIGNMENT Unit 9 Methods, Arrays, and the Java Standard Class Library Reimplementing the Arrays class (60 points) The Arrays class, which is also part of the Java standard class library, provides various class methods that perform common tasks on arrays, such as searching and sorting. Write a public class called MyArrays, which provides some of the functionality which is...

  • Use BlueJ to write a program that reads a sequence of data for several car objects...

    Use BlueJ to write a program that reads a sequence of data for several car objects from an input file. It stores the data in an ArrayList<Car> list . Program should work for input file containing info for any number of cars. (You should not assume that it will always be seven lines in the input file). Use notepad to create input file "inData.txt". File should be stored in the same folder where all files from BlueJ for this program...

  • JAVA programming The task of parsing a file for correctness is an essential part of any...

    JAVA programming The task of parsing a file for correctness is an essential part of any programmer toolkit. The check for a balanced set of brackets in a file a Stack can be used and the following algorithm: • The source file is read character by character • Each time an opening '{' is read it is pushed onto the stack • Each time a closing '}' is read the stack is popped • If the stack is empty when...

  • !!!!!!!Java!!!!! When you are confident that your methods work properly and that you can generate random...

    !!!!!!!Java!!!!! When you are confident that your methods work properly and that you can generate random text with my generateText method, you can move on to the second step. Create a third class called Generator within the cs1410 package. Make class. This class should have a main method that provides a user interface for random text generation. Your interface should work as follows: Main should bring up an input dialog with which the user can enter the desired analysis level...

  • *** FOR A BEGINNER LEVEL JAVA CLASS, PLEASE KEEP CODE SIMPLE, AND WE USE BLUE J...

    *** FOR A BEGINNER LEVEL JAVA CLASS, PLEASE KEEP CODE SIMPLE, AND WE USE BLUE J IN CLASS (IF IT DOESNT MATTER PLEASE COMMENT TELLING WHICH PROGRAM YOU USED TO WRITE THE CODE, PREFERRED IS BLUE J!!)*** ArrayList of Objects and Input File Use BlueJ to write a program that reads a sequence of data for several car objects from an input file. It stores the data in an ArrayList<Car> list . Program should work for input file containing info...

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