Sentiment Word Detector
Let us create a java program to find the sentiment words in the input. The words are created in two categories such as positive or negative. The program finds the words and prints it as the output. This is one of the sample programs in AI coding in beginner’s level.
Steps to follow:
- This program begins by importing java.util package.
- A public class is created. The class name is “SwordDetector”. It includes the main () function.
- Positive and negative words are created as set of string.
- Using Scanner object, the system input is read from the user.
- Each and all words are separated. Each word is compared with positive and negative words list.
- Finally, check the category of the word and print it accordingly.
Program:
import java.util.*;
public class SwordDetector {
public static void
main(String[] args) {
// create a
simple positive and negative words
Set<String> posWords = new HashSet<>(Arrays.asList(
"happy", "good", "great", "day",
"excellent", "marvellous", "wonderful",
"nice", "positive","Hope","confident","fortune","luck"
));
Set<String> negWords = new HashSet<>(Arrays.asList(
"sad", "poor","hate", "bad",
"awful","negative", "angry",
"worse","bad day"
));
Scanner s1 =
new Scanner(System.in);
System.out.println("Enter the sentence:");
String in1 =
s1.nextLine().toLowerCase();
// Let us
Split sentence into words
String[]
s_words = in1.split("\\s+");
int posCount =
0;
int negCount =
0;
// create a
Count of positive and negative words
for (String
word : s_words) {
if
(posWords.contains(word)) {
posCount++;
} else if
(negWords.contains(word)) {
negCount++;
}
}
// Decide the
sentiment words
if (posCount
> negCount) {
System.out.println("Sentiment: It is Positive");
} else if
(negCount > posCount) {
System.out.println("Sentiment: It is Negative");
} else {
System.out.println("Sentiment: Neutral 😐");
}
}
}
Output:
Compile and run the program to get the output.
Enter the sentence:
Good morning. Have a nice day!
Sentiment: It is Positive
Yes. The program is completed.
Hope, this code is useful to you. This is the basic java
program in terms of AI programming. Keep Coding!!!
Comments
Post a Comment