-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsentiment_analyzer.py
86 lines (58 loc) · 2.11 KB
/
sentiment_analyzer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import pandas as pd
from utils import logger
nltk.download("vader_lexicon", quiet=True)
def create_dataframe_from_comments(all_comments: list) -> pd.DataFrame:
"""Create a dataframe from comments
:type all_comments: list
:param all_comments: List of comments
:rtype: pd.DataFrame
:returns: Pandas dataframe
"""
df = pd.DataFrame(list(all_comments), columns=["Original Comment Text"])
return df
def analyze_comments(dataframe: pd.DataFrame) -> pd.DataFrame:
"""Analyze comments by calculating polarity scores
Add Sentiment Score and Sentiment columns to the dataframe.
:type dataframe: pd.DataFrame
:param dataframe: Comments dataframe
:rtype: pd.DataFrame
:returns: Dataframe with sentiment analysis results
"""
logger.info("Performing sentiment analysis on comments...")
analyzer = SentimentIntensityAnalyzer()
dataframe["Sentiment Score"] = dataframe["Cleaned Comment Text"].apply(
lambda comment: _get_polarity_score(analyzer, comment)
)
dataframe["Sentiment"] = dataframe["Sentiment Score"].apply(
lambda score: _convert_score_to_sentiment(score)
)
return dataframe
def _get_polarity_score(analyzer: SentimentIntensityAnalyzer, text: str) -> float:
"""Calculate polarity score for the given text
:type analyzer: SentimentIntensityAnalyzer
:param analyzer: Sentiment analyzer for Vader model
:type text: str
:param text: Cleaned comment text
:rtype: float
:returns: Polarity score
"""
scores = analyzer.polarity_scores(text)
logger.debug(f"Text: {text}, Scores: {scores}")
return scores["compound"]
def _convert_score_to_sentiment(score) -> str:
"""Convert score to sentiment
:type score: float
:param score: Polarity score
:rtype: str
:returns: Sentiment as Positive, Negative, or Neutral
"""
sentiment = ""
if score <= -0.5:
sentiment = "Negative"
elif -0.5 < score <= 0.5:
sentiment = "Neutral"
else:
sentiment = "Positive"
return sentiment