SentimentAnalyzer.py
1.55 KB
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
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
with open(BASE_DIR + 'sentiment.txt', 'w', encoding='utf-8-sig') as txt_file:
txt_file.write(str(tot))
txt_file.write(str(int(positive / tot * 100)))
txt_file.write(str(int(neutral / tot * 100)))
txt_file.write(str(int(negative / tot * 100)))
print("txt file saved")
# return tot, positive, neutral, negative
def analyze(filename):
client = language_v1.LanguageServiceClient()
# try:
with open(filename, "r", encoding='utf-8-sig') as file:
# Instantiates a plain text document.
content = file.read()
document = language_v1.Document(content=content, type_=language_v1.Document.Type.PLAIN_TEXT)
annotations = client.analyze_sentiment(request={'document': document})
GetResult(annotations)
# except:
# return 0, 0, 0, 0
def StartSentimentAnalysis():
analyze("data.txt")