Code HS Consumer Review Lab

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Open your existing SimpleReview.txt file and annotate each adjective by adding a "*" at the beginning of the word. For example, the SimpleReview.txt from Activity 2 would be:

This was a *terrible restaurant! The pizza crust was too *chewy, and I disliked the pasta. I would definitely not come back.

Part 1.4.1 (Review.Java) In this activity you'll write a new method modeled off the fakeReview method you wrote in Activity 3. The method will be redesigned so that it will make reviews stronger; that is, either more negative or more positive. Use the positiveOrNegative method provided in the Review class to write your new method, and name it after the type of fake review you plan on making. Remember, we can determine how positive or negative an adjective is by using our sentimentVal method. If a word is above a specific threshold (0), that word is positive!

import java.util.Scanner; import java.io.File; import java.util.HashMap; import java.util.ArrayList; import java.util.Random; import java.io.*; /** * Class that contains helper methods for the Review Lab **/ public class Review { private static HashMap<String, Double> sentiment = new HashMap<String, Double>(); private static ArrayList<String> posAdjectives = new ArrayList<String>(); private static ArrayList<String> negAdjectives = new ArrayList<String>(); private static final String SPACE = " "; static{ try { Scanner input = new Scanner(new File("cleanSentiment.csv")); while(input.hasNextLine()){ String[] temp = input.nextLine().split(","); sentiment.put(temp[0],Double.parseDouble(temp[1])); //System.out.println("added "+ temp[0]+", "+temp[1]); } input.close(); } catch(Exception e){ System.out.println("Error reading or parsing cleanSentiment.csv"); } //read in the positive adjectives in postiveAdjectives.txt try { Scanner input = new Scanner(new File("positiveAdjectives.txt")); while(input.hasNextLine()){ String temp = input.nextLine().trim(); posAdjectives.add(temp); } input.close(); } catch(Exception e){ System.out.println("Error reading or parsing postitiveAdjectives.txt\n" + e); } //read in the negative adjectives in negativeAdjectives.txt try { Scanner input = new Scanner(new File("negativeAdjectives.txt")); while(input.hasNextLine()){ negAdjectives.add(input.nextLine().trim()); } input.close(); } catch(Exception e){ System.out.println("Error reading or parsing negativeAdjectives.txt"); } } /** * returns a string containing all of the text in fileName (including punctuation), * with words separated by a single space */ public static String textToString( String fileName ) { String temp = ""; try { Scanner input = new Scanner(new File(fileName)); //add 'words' in the file to the string, separated by a single space while(input.hasNext()){ temp = temp + input.next() + " "; } input.close(); } catch(Exception e){ System.out.println("Unable to locate " + fileName); } //make sure to remove any additional space that may have been added at the end of the string. return temp.trim(); } /** * @returns the sentiment value of word as a number between -1 (very negative) to 1 (very positive sentiment) */ public static double sentimentVal( String word ) { try { return sentiment.get(word.toLowerCase()); } catch(Exception e) { return 0; } } /** * Returns the ending punctuation of a string, or the empty string if there is none */ public static String getPunctuation( String word ) { String punc = ""; for(int i=word.length()-1; i >= 0; i--){ if(!Character.isLetterOrDigit(word.charAt(i))){ punc = punc + word.charAt(i); } else { return punc; } } return punc; } /** * Randomly picks a positive adjective from the positiveAdjectives.txt file and returns it. */ public static String randomPositiveAdj() { int index = (int)(Math.random() * posAdjectives.size()); return posAdjectives.get(index); } /** * Randomly picks a negative adjective from the negativeAdjectives.txt file and returns it. */ public static String randomNegativeAdj() { int index = (int)(Math.random() * negAdjectives.size()); return negAdjectives.get(index); } /** * Randomly picks a positive or negative adjective and returns it. */ public static String randomAdjective() { boolean positive = Math.random() < .5; if(positive){ return randomPositiveAdj(); } else { return randomNegativeAdj(); } } public static double totalSentiment(String fileName) { String placeholder = ""; double totalSentiment = 0.0; String review = textToString(fileName); //removes punctuation review = review.replaceAll("\\p{Punct}", ""); for (int i = 0; i < review.length(); i++) { if (review.substring(i, i + 1).equals(" ")) { totalSentiment += sentimentVal(placeholder); placeholder = ""; }else{ placeholder += review.substring(i, i + 1); } } return totalSentiment; } public static int starRating(String fileName) { double totalSentiment = totalSentiment(fileName); if(totalSentiment > 15) { return 4; } else if(totalSentiment > 10) { return 3; } else if(totalSentiment > 5) { return 2; } else if(totalSentiment > 0) { return 1; } else { return 0; } } public static String fakeReview(String fileName) { String review = textToString(fileName); String fake = ""; for(int i = 0; i < review.length()-1; i++) { if(review.substring(i, i+1).equals("*")) { i++; String replace = ""; boolean isWord = true; while(isWord) { replace += review.substring(i, i+1); i++; if(review.substring(i, i+1).equals(" ")) { isWord = false; } } replace = replace.replaceAll("\\p{Punct}", ""); replace = randomAdjective() + " "; fake += replace; }else { fake += review.substring(i, i+1); } } return fake; } public static String fakeReviewStronger(String fileName) { String review = textToString(fileName); String fake = " "; for(int i = 0; i < review.length()-1; i++) { if(review.substring(i, i+1).equals("*")) { i++; String replace = ""; boolean isWord = true; while(isWord) { replace += review.substring(i, i+1); i++; if(review.substring(i, i+1).equals(" ")) { isWord = false; } } replace = replace.replaceAll("\\p{Punct}", ""); if(sentimentVal(replace) > 0) { replace = randomPositiveAdj() + " "; }else if (sentimentVal(replace) < 0) { replace = randomNegativeAdj()+ " "; }else { replace = randomAdjective() + " "; } fake += replace; }else { fake += review.substring(i, i+1); } } return fake; } }

1.5.1 Final Activity Next under myLittlePony.java put this:

import java.util.Scanner; import java.io.File; public class myLittlePony { public static String txtString(String file) { String blank = ""; try { Scanner s = new Scanner(new File(file)); while(s.hasNext()){ blank = blank + s.next() + " "; } s.close(); } catch(Exception e){ System.out.println("Unable to locate " + file); } return blank.trim(); } public static String replace(String wrd, String letToRep, String letToIn) { String rpl = ""; for(int i = 0; i < wrd.length(); i++) { String let = wrd.substring(i, i + 1); if(let.equals(letToRep)) { rpl += letToIn; } else { rpl += let; } } return rpl; } }

1.5.1 Final Activity Finally under MyProgram.java put:

import java.util.Scanner; public class MyProgram { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("Here are your words:"); String word = myLittlePony.txtString("yourmom.txt"); System.out.println(word); System.out.println("Enter the letter you want to replace:"); String letter = s.nextLine(); System.out.println("Enter the replacing letter:"); String replacing = s.nextLine(); System.out.println(myLittlePony.replace(word, letter, replacing)); } }

Write down the method signature. Does this method require a parameter? If so, what type of parameter is required? What happens if you pass a different type of parameter instead? Does the method return a value? If so, what is the return type? Write code that tests the sentimentVal method by calling it with several different String parameters and printing out the return value. Any words not in the list will have a return value of zero. Make sure to keep calling the method until you have at least three strings that have a return value other than zero. Record the method calls, including provided strings and return values.

1.sentimentVal(String) 2. A String parameter is required. Passing a different parameter would result in an error. 3. The value returned is a double. 4.System.out.print(Review.sentimentVal("acceptible")); --> returns -0.12 System.out.print(Review.sentimentVal("acceptible")); System.out.print(Review.sentimentVal("happily")); System.out.print(Review.sentimentVal("cold"));

Which of the following method calls to sentimentVal would compile correctly? I. double num = sentimentVal("warm"); II. String word = sentimentVal(0.5); III. double x = sentimentVal("good", "bad");

I only

1.5.1 Final Activity Ok in yourmom.txt you'll need this or whatever other text string you want:

Im just trying to be your mother I will never give you up and youll never let me down you silly goose

1.5.1 Final Activity To do this correctly you will need to make 2 extra files (you should already have MyProgram.java): yourmom.txt and myLittlePony.java to make this correctly

Just do it or I mean you could change the names of the files it's up to you

Test the totalSentimentmethod in the ReviewTester class by calling totalSentiment("SimpleReview.txt") and printing the returned value. It should return -2.92.

public class ReviewTester { public static void main(String[] args) { //Test the sentimentVal method here! double answer = Review.totalSentiment("SimpleReview.txt"); System.out.print(answer); double star = Review.starRating("SimpleReview.txt"); System.out.print(star); } }

Part 1.4.1 (ReviewTester.Java) In this activity you'll write a new method modeled off the fakeReview method you wrote in Activity 3. The method will be redesigned so that it will make reviews stronger; that is, either more negative or more positive. Use the positiveOrNegative method provided in the Review class to write your new method, and name it after the type of fake review you plan on making. Remember, we can determine how positive or negative an adjective is by using our sentimentVal method. If a word is above a specific threshold (0), that word is positive!

public class ReviewTester { public static void main(String[] args) { //Test your positive or negative fakeReview here! String pn = Review.fakeReviewStronger("SimpleReview.txt"); System.out.print(pn); } }

Write the method fakeReview. The method signature is given below. public static String fakeReview(String fileName) The parameter fileName should be the name of the annotated review (with "*" at the beginning of the adjectives). The fakeReview method should loop over the String containing the contents of the marked-up review to build and return a fake review. Remember, you are replacing only the adjectives with a random positive or negative adjective, which are marcated with a *. You are going to want to take advantage of the method randomPositiveAdj that returns a random word from the positiveAdjective.txt files. Feel free to add more adjectives to those files if you want those words to be used!

public static String fakeReview(String fileName) { String fileTxt = textToString(fileName); String answer = " "; int index = fileTxt.indexOf("*"); while(index > 1) { int space = fileTxt.indexOf(" ", index); answer += fileTxt.substring(0, index); String pun = ""; if (space == -1) { pun = getPunctuation(fileTxt); fileTxt = ""; } else { String wrd = fileTxt.substring(index + 1, space); pun = getPunctuation(wrd); pun += " "; fileTxt = fileTxt.substring(space + 1); } answer += randomPositiveAdj(); answer += pun; index = fileTxt.indexOf("*"); } answer += fileTxt; return answer; } }

In the Review.java file: Write the following method that determines the sentiment value of a review: This method will take a .txt file as an input, and return the total review value of each word associated with the review. In order to complete this, you are going to need to use the method textToString that has been provided. This will convert the formal parameter fileName into a single String that can then be manipulated to get the correct answer. Your method should traverse the entire String looking for each individual word in the review. Once you have a full word, that word should be run through the sentimentVal method, and the value calculated should be saved in a running sum variable. Some words are going to have punctuation marks attached to them. Utilize the getPunctuation and or removePunctuation methods to figure out if a word has punctuation, and remove it before running the word through the sentimentVal search.

public static double totalSentiment(String fileName) { String txtFile = textToString(fileName); double total = 0; while(txtFile.length() > 0) { int space = txtFile.indexOf(" "); String wrd; if(space > -1) { wrd = txtFile.substring(0, space); txtFile = txtFile.substring(space + 1); } else { wrd = txtFile; txtFile = ""; } wrd = removePunctuation(wrd); total += sentimentVal(wrd); } return total; }

Write the following method in the Review class that determines the star rating of a review. public static int starRating(String fileName) The starRating method takes a .txt file, finds the totalSentiment and returns a rating from 0-4 based on the total review score. The rating is set in intervals of 10 starting at -10. For example, if the totalSentiment is lower than -10, the starRating would be 0. If the totalSentiment is less than 0, the starRating would be 1, and so forth.

public static int starRating(String fileName) { double totalSentiment = totalSentiment(fileName); if(totalSentiment < -10) { return 0; } else if(totalSentiment < 0) { return 1; } else if(totalSentiment < 10) { return 2; } else if(totalSentiment < 20) { return 3; } else { return 4; } } }


Ensembles d'études connexes

CWTS-2-Introduction to Wireless Local Area Networking

View Set

Lección 15 Lesson Test Review 1-Escuchar; 2- Imágenes; 3-Completar; 4-Opciones; 5-Oraciones; 6-Completar; 7-Escoger; 8-Oraciones; 9-Ayer; 10 Lectura"Beber Alcohol" (corrected)

View Set

Chapter 23: Adult Women and Men (FINAL EXAM)

View Set

Module 5 Speaking Questions : Questions - French

View Set

UNMC health assessment exam 4 practice questions

View Set

el gran robo argentino sentences

View Set

Legal Concepts of the insurance Contract- chapter 2

View Set

ACCT 3230 - Chapter 14 - LearnSmart

View Set