SentimentAnalyzer.py 1.25 KB
import argparse
import os

from google.cloud import language_v1

BASE_DIR = os.path.dirname(os.path.realpath(__file__))
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = BASE_DIR + "/artful-fortress-316201-f135fd520d56.json"

def GetResult(annotations):
    score = annotations.document_sentiment.score
    magnitude = annotations.document_sentiment.magnitude

    tot = 0
    positive = 0
    negative = 0
    neutral = 0
    for index, sentence in enumerate(annotations.sentences):
        sentence_sentiment = sentence.sentiment.score
        if sentence_sentiment > 0:
            positive += 1
        elif sentence_sentiment < 0:
            negative += 1
        else:
            neutral += 1
        tot += 1
    return tot, positive, neutral, negative

def analyze(movie_review_filename):
    client = language_v1.LanguageServiceClient()

    with open(movie_review_filename, "r", encoding='utf-8-sig') as review_file:
        # Instantiates a plain text document.
        content = review_file.read()
    document = language_v1.Document(content=content, type_=language_v1.Document.Type.PLAIN_TEXT)
    annotations = client.analyze_sentiment(request={'document': document})

    return GetResult(annotations)

def StartSentimentAnalysis():
    return analyze("data.txt")