/
sentimentPackage.py
85 lines (64 loc) · 2.77 KB
/
sentimentPackage.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
'''
This module computes the sentiments based on input text.
It reads a list of sentiment depicting words from Sentiment database
and computes the sentiment value.
Author : Naresh Pratap Singh
E-Mail : MAIL2NARESH@GMAIL.COM
Date : Jan 17 2011
Project Advisor : Prof. Steven Skiena
'''
import siteConfig
import errorStrings, debugTrace
import sys
import re
class sentimentPackage:
sentimentFile = siteConfig.sentimentMainFile
sentimentDelim = '|'
sentimentDict = {}
debugEnabled = False
errorStringsInst = None
debugTraceInst = None
def __init__(self, debugEnabled = False):
try:
self.debugEnabled = debugEnabled
self.errorStringsInst = errorStrings.errorStrings()
self.debugTraceInst = debugTrace.debugTrace(self.debugEnabled)
hSentimentFile = open(self.sentimentFile)
for line in hSentimentFile.readlines():
items = line.split(self.sentimentDelim)
self.sentimentDict [items [0]] = (items [1], items [2], int(items[3]))
hSentimentFile.close()
except:
hSentimentFile.close()
self.debugTraceInst.doPrintTrace(self.errorStringsInst.getResourceNotFoundError(), sys.exc_info() [1])
def constructRegEx(self, word):
return r'\b' + word + r'\b'
def computeSentiment(self, message):
positiveSentiment = 0
negativeSentiment = 0
negativeWords = []
positiveWords = []
totalCount = len(message.split(' '))
for key in self.sentimentDict.keys():
wordCount = self.countWords(key, message)
if self.sentimentDict [key][2] == -1:
negativeSentiment += wordCount
if wordCount != 0:
negativeWords.append(key)
else:
positiveSentiment += wordCount
if wordCount != 0:
positiveWords.append(key)
return (positiveSentiment, positiveWords, negativeSentiment, negativeWords, totalCount)
def countWords(self, word, message):
regEx = self.constructRegEx(word)
regObj = re.compile(regEx)
wordList = regObj.findall(message)
if wordList != None:
return len(wordList)
else:
return 0
if __name__ == "__main__":
sent = sentimentPackage(True)
dir(sent)
print sent.computeSentiment("hi This is a test program xoxo")