Hi~ Thank you so much for your patience. I made some modification to the code according to your suggestion and it worked out!! However, the result is the tone of the whole text I test on, but I want to get the tone of each sentence in the text, what modification do I need to add on the code? Thank you again for your time!! | [reply] |
Where you have print "%positive\n"; you should have print "positive: $sentence\n"; and the same for negative and neutral.
| [reply] [d/l] [select] |
#!/usr/bin/perl
use warnings;
use Algorithm::NaiveBayes;
my $pos_file = '/Users/Agnes/Documents/positive.TXT';
my $neg_file = '/Users/Agnes/Documents/negative.txt';
my $neu_file = '/Users/Agnes/Documents/neutral.txt';
my $categorizer = Algorithm::NaiveBayes->new;
my $fh;
open($fh,"<",$pos_file) or die "Could not open $pos_file: $!";
while (my $sentence = <$fh>) {
chomp $sentence;
my @words = split(' ',$sentence);
my %positive;
$positive{$_}++ for @words;
$categorizer->add_instance(
attributes => \%positive,
label => 'positive');
}
close($fh);
open($fh,"<",$neg_file) or die "Could not open $neg_file: $!";
while (my $sentence = <$fh>) {
chomp $sentence;
my @words = split(' ',$sentence);
my %negative;
$negative{$_}++ for @words;
$categorizer->add_instance(
attributes => \%negative,
label => 'negative');
}
close($fh);
open($fh,"<",$neu_file) or die "Could not open $neg_file: $!";
while (my $sentence = <$fh>) {
chomp $sentence;
my @words = split(' ',$sentence);
my %neutral;
$neutral{$_}++ for @words;
$categorizer->add_instance(
attributes => \%neutral,
label => 'neutral');
}
close($fh);
$categorizer->train;
my $sentence_file = '/Users/Agnes/Documents/process_sentence.txt';
open($fh,"<",$sentence_file) or die "Could not open $sentence_file: $!
+";
while (my $sentence = <$fh>) {
chomp $sentence;
my @words = split(' ',$sentence);
my %test;
$test{$_}++ for @words;
my $probability = $categorizer->predict(attributes => \%test);
if ( $probability->{positive} > 1/3 ) {
print "%positive:$sentence\n";
}
if ( $probability->{negative} > 1/3 ) {
print "%negative:$sentence\n";
}
if ( $probability->{neutral} > 1/3 ) {
print "%neutral:$sentence\n";
}
}
close($fh);
# if ( $probability->{negative} > 1/3 ) {
#print "%negative\n";
#}
#if ( $probability->{neutral} > 1/3 ) {
# print "%neutral\n";
#}
I do not know what should I do next. It will be very kind of you to help me to solve this problem. Thank you!! | [reply] [d/l] |