Showing
1 changed file
with
42 additions
and
0 deletions
SentimentAnalyzer.py
0 → 100644
1 | +import argparse | ||
2 | + | ||
3 | +from google.cloud import language_v1 | ||
4 | + | ||
5 | +def print_result(annotations): | ||
6 | + score = annotations.document_sentiment.score | ||
7 | + magnitude = annotations.document_sentiment.magnitude | ||
8 | + | ||
9 | + tot = 0 | ||
10 | + positive = 0 | ||
11 | + negative = 0 | ||
12 | + neutral = 0 | ||
13 | + for index, sentence in enumerate(annotations.sentences): | ||
14 | + sentence_sentiment = sentence.sentiment.score | ||
15 | + if sentence_sentiment > 0: | ||
16 | + positive += 1 | ||
17 | + elif sentence_sentiment < 0: | ||
18 | + negative += 1 | ||
19 | + else: | ||
20 | + neutral += 1 | ||
21 | + # print( | ||
22 | + # "Sentence {} has a sentiment score of {}".format(index, sentence_sentiment) | ||
23 | + # ) | ||
24 | + tot += 1 | ||
25 | + print( | ||
26 | + "Overall Sentiment: score of {} with magnitude of {}".format(score, magnitude) | ||
27 | + ) | ||
28 | + return tot, positive, negative | ||
29 | + | ||
30 | +def analyze(movie_review_filename): | ||
31 | + client = language_v1.LanguageServiceClient() | ||
32 | + | ||
33 | + with open(movie_review_filename, "r", encoding='utf-8-sig') as review_file: | ||
34 | + # Instantiates a plain text document. | ||
35 | + content = review_file.read() | ||
36 | + document = language_v1.Document(content=content, type_=language_v1.Document.Type.PLAIN_TEXT) | ||
37 | + annotations = client.analyze_sentiment(request={'document': document}) | ||
38 | + | ||
39 | + print_result(annotations) | ||
40 | + | ||
41 | +if __name__ == "__main__": | ||
42 | + analyze("data.txt") | ||
... | \ No newline at end of file | ... | \ No newline at end of file |
-
Please register or login to post a comment