RuleBasedSentimentAnalyzer

Struct RuleBasedSentimentAnalyzer 

Source
pub struct RuleBasedSentimentAnalyzer { /* private fields */ }
Expand description

Advanced rule-based sentiment analyzer

Implementations§

Source§

impl RuleBasedSentimentAnalyzer

Source

pub fn new(lexicon: SentimentLexicon) -> Self

Create a new rule-based sentiment analyzer

Source

pub fn with_basiclexicon() -> Self

Create an analyzer with a basic lexicon

Examples found in repository?
examples/sentiment_analysis_demo.rs (line 12)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("Sentiment Analysis Demo");
8    println!("======================\n");
9
10    // Create sentiment analyzers
11    let basic_analyzer = LexiconSentimentAnalyzer::with_basiclexicon();
12    let rule_based_analyzer = RuleBasedSentimentAnalyzer::with_basiclexicon();
13
14    // Example texts for analysis
15    let texts = vec![
16        "I absolutely love this product! It's amazing!",
17        "This is terrible, I hate it.",
18        "It's okay, nothing special.",
19        "I'm not happy with this purchase.",
20        "Extremely disappointed with the quality.",
21        "This is very good, I'm really satisfied.",
22        "The worst experience ever!",
23        "Somewhat decent, but could be better.",
24    ];
25
26    println!("Basic Lexicon-based Sentiment Analysis:");
27    println!("======================================");
28
29    for text in &texts {
30        let result = basic_analyzer.analyze(text)?;
31        println!("\nText: \"{text}\"");
32        println!("  Sentiment: {:?}", result.sentiment);
33        println!("  Score: {:.2}", result.score);
34        println!("  Confidence: {:.2}%", result.confidence * 100.0);
35        println!(
36            "  Word counts: +{} -{} ={} (total: {})",
37            result.word_counts.positive_words,
38            result.word_counts.negative_words,
39            result.word_counts.neutral_words,
40            result.word_counts.total_words
41        );
42    }
43
44    println!("\n\nRule-based Sentiment Analysis:");
45    println!("=============================");
46
47    // Examples with intensifiers
48    let intensifiedtexts = vec![
49        "This is good",
50        "This is very good",
51        "This is extremely good",
52        "This is somewhat good",
53        "This is really bad",
54        "This is slightly bad",
55    ];
56
57    for text in &intensifiedtexts {
58        let basic_result = basic_analyzer.analyze(text)?;
59        let rule_result = rule_based_analyzer.analyze(text)?;
60
61        println!("\nText: \"{text}\"");
62        println!("  Basic score: {:.2}", basic_result.score);
63        println!("  Rule-based score: {:.2}", rule_result.score);
64        println!(
65            "  Difference: {:.2}",
66            rule_result.score - basic_result.score
67        );
68    }
69
70    // Batch analysis example
71    println!("\n\nBatch Analysis:");
72    println!("==============");
73
74    let batchtexts = vec![
75        "Great product!",
76        "Terrible service.",
77        "Average quality.",
78        "Highly recommended!",
79        "Would not buy again.",
80    ];
81
82    let batch_results = basic_analyzer.analyze_batch(&batchtexts)?;
83
84    for (text, result) in batchtexts.iter().zip(batch_results.iter()) {
85        println!(
86            "{}: {:?} (score: {:.2})",
87            text, result.sentiment, result.score
88        );
89    }
90
91    // Creating a custom lexicon
92    println!("\n\nCustom Lexicon Example:");
93    println!("======================");
94
95    let mut custom_lexicon = SentimentLexicon::new();
96    custom_lexicon.add_word("awesome".to_string(), 3.0);
97    custom_lexicon.add_word("terrible".to_string(), -3.0);
98    custom_lexicon.add_word("meh".to_string(), -0.5);
99
100    let custom_analyzer = LexiconSentimentAnalyzer::new(custom_lexicon);
101
102    let customtexts = vec![
103        "This is awesome!",
104        "Meh, not impressed",
105        "Terrible experience",
106    ];
107
108    for text in &customtexts {
109        let result = custom_analyzer.analyze(text)?;
110        println!(
111            "\n\"{}\" -> {:?} (score: {:.2})",
112            text, result.sentiment, result.score
113        );
114    }
115
116    Ok(())
117}
Source

pub fn analyze(&self, text: &str) -> Result<SentimentResult>

Analyze sentiment with rule modifications

Examples found in repository?
examples/sentiment_analysis_demo.rs (line 59)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("Sentiment Analysis Demo");
8    println!("======================\n");
9
10    // Create sentiment analyzers
11    let basic_analyzer = LexiconSentimentAnalyzer::with_basiclexicon();
12    let rule_based_analyzer = RuleBasedSentimentAnalyzer::with_basiclexicon();
13
14    // Example texts for analysis
15    let texts = vec![
16        "I absolutely love this product! It's amazing!",
17        "This is terrible, I hate it.",
18        "It's okay, nothing special.",
19        "I'm not happy with this purchase.",
20        "Extremely disappointed with the quality.",
21        "This is very good, I'm really satisfied.",
22        "The worst experience ever!",
23        "Somewhat decent, but could be better.",
24    ];
25
26    println!("Basic Lexicon-based Sentiment Analysis:");
27    println!("======================================");
28
29    for text in &texts {
30        let result = basic_analyzer.analyze(text)?;
31        println!("\nText: \"{text}\"");
32        println!("  Sentiment: {:?}", result.sentiment);
33        println!("  Score: {:.2}", result.score);
34        println!("  Confidence: {:.2}%", result.confidence * 100.0);
35        println!(
36            "  Word counts: +{} -{} ={} (total: {})",
37            result.word_counts.positive_words,
38            result.word_counts.negative_words,
39            result.word_counts.neutral_words,
40            result.word_counts.total_words
41        );
42    }
43
44    println!("\n\nRule-based Sentiment Analysis:");
45    println!("=============================");
46
47    // Examples with intensifiers
48    let intensifiedtexts = vec![
49        "This is good",
50        "This is very good",
51        "This is extremely good",
52        "This is somewhat good",
53        "This is really bad",
54        "This is slightly bad",
55    ];
56
57    for text in &intensifiedtexts {
58        let basic_result = basic_analyzer.analyze(text)?;
59        let rule_result = rule_based_analyzer.analyze(text)?;
60
61        println!("\nText: \"{text}\"");
62        println!("  Basic score: {:.2}", basic_result.score);
63        println!("  Rule-based score: {:.2}", rule_result.score);
64        println!(
65            "  Difference: {:.2}",
66            rule_result.score - basic_result.score
67        );
68    }
69
70    // Batch analysis example
71    println!("\n\nBatch Analysis:");
72    println!("==============");
73
74    let batchtexts = vec![
75        "Great product!",
76        "Terrible service.",
77        "Average quality.",
78        "Highly recommended!",
79        "Would not buy again.",
80    ];
81
82    let batch_results = basic_analyzer.analyze_batch(&batchtexts)?;
83
84    for (text, result) in batchtexts.iter().zip(batch_results.iter()) {
85        println!(
86            "{}: {:?} (score: {:.2})",
87            text, result.sentiment, result.score
88        );
89    }
90
91    // Creating a custom lexicon
92    println!("\n\nCustom Lexicon Example:");
93    println!("======================");
94
95    let mut custom_lexicon = SentimentLexicon::new();
96    custom_lexicon.add_word("awesome".to_string(), 3.0);
97    custom_lexicon.add_word("terrible".to_string(), -3.0);
98    custom_lexicon.add_word("meh".to_string(), -0.5);
99
100    let custom_analyzer = LexiconSentimentAnalyzer::new(custom_lexicon);
101
102    let customtexts = vec![
103        "This is awesome!",
104        "Meh, not impressed",
105        "Terrible experience",
106    ];
107
108    for text in &customtexts {
109        let result = custom_analyzer.analyze(text)?;
110        println!(
111            "\n\"{}\" -> {:?} (score: {:.2})",
112            text, result.sentiment, result.score
113        );
114    }
115
116    Ok(())
117}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V