-
Notifications
You must be signed in to change notification settings - Fork 0
/
corpusReader.py
246 lines (197 loc) · 8.2 KB
/
corpusReader.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
from __future__ import division
import config
import re
from nltk.metrics import BigramAssocMeasures
from nltk.probability import FreqDist, ConditionalFreqDist
from nltk.tokenize.regexp import RegexpTokenizer
from nltk.corpus.reader import CategorizedPlaintextCorpusReader as Reader
class PolarityDataReader(object):
"""
PolarityDataReader:
Reader for POS/NEG Categorized Sentiword data
uses:
nltk.corpus.reader.CategorizedPlaintextCorpusReader
usage:
dataReader = PolarityDataReader([rootLocation],[readerObject])
dataReader.getDocuments()
dataReader.setTerms([No:ofTerms])
featuresets = dataReader.getTermDocMatrix()
"""
def __init__(self, rootLocation = config.POLARITY_DATASET,reader=None):
super(PolarityDataReader, self).__init__()
if reader == None:
self.reader = Reader(rootLocation,r'.*/.*', cat_pattern=r'(.*)/.*')
else:
self.reader = reader
self.setStopWords()
self.documents = None;
self.terms = None;
def getDocuments(self):
if not self.documents:
self.documents = [(list(self.reader.words(fileid)), category)
for category in self.reader.categories()
for fileid in self.reader.fileids(category)]
return self.documents;
def setStopWords(self,fileLocation = config.STOP_WORDS_FILE):
stopfile = open(fileLocation, 'r')
self.stopwords = stopfile.read().split()
def removeStopWords(self,wordList):
""" Remove common words which have no search value """
return [word for word in wordList if word not in self.stopwords]
def setTerms(self,size=2000,featureSelection='PD',removeStopWords=True):
if featureSelection == 'PD':
self.__setTermsPD__(size)
print "Feature Selection : PD :done "
elif featureSelection == 'CHI_SQUARE':
self.__setTermsCHISQUARE__(size)
print "Feature Selection : CHI_SQUARE :done "
elif featureSelection == 'SWNSS':
self.__setTermsSWNSS__(size)
print "Feature Selection : SWNPD :done "
else:
"""
geting most frequent Words
"""
all_words = [w.lower() for w in self.reader.words()];
if removeStopWords:
all_words = self.removeStopWords(all_words);
all_words = FreqDist(w for w in all_words)
self.terms = all_words.keys()[:size]
print "Feature Selection: frequent Words :done "
def documentFeatures(self,document,sentiwordnet=False):
document_words = set(document)
features = {}
if sentiwordnet:
pass
#TODO
else :
for word in self.terms:
features[word] = (word in document_words)
return features
def getTermDocMatrix(self):
return [(self.documentFeatures(document), category)
for (document,category) in self.documents]
def __setTermsPD__(self,size):
"""
score=|(posDF-negDF)|/(posDF+negDF)
"""
posWord = {};
negWord = {};
for word in self.reader.words(categories = ['pos']):
inc(posWord,word.lower());
for word in self.reader.words(categories = ['neg']):
inc(negWord,word.lower());
wordScores = {}
for word in self.reader.words():
try:
posScore = posWord[word]
except KeyError, e:
posScore = 0
try:
negScore = negWord[word]
except KeyError, e:
negScore = 0
totalScore = posScore + negScore
if totalScore <= 10 : # min total count
wordScores[word] = 0.1
else :
wordScores[word] = abs(posScore-negScore)/totalScore
#removeStopWords does no affect accurcy
termScore = sorted(wordScores.items(),key=lambda(w,s):s,reverse=True)[:size]
self.terms = [w for (w,s) in termScore];
def __setTermsCHISQUARE__(self,size):
word_fd = FreqDist()
label_word_fd = ConditionalFreqDist()
for word in self.reader.words(categories=['pos']):
word_fd.inc(word.lower())
label_word_fd['pos'].inc(word.lower())
for word in self.reader.words(categories=['neg']):
word_fd.inc(word.lower())
label_word_fd['neg'].inc(word.lower())
pos_word_count = label_word_fd['pos'].N()
neg_word_count = label_word_fd['neg'].N()
total_word_count = pos_word_count + neg_word_count
wordScores = {}
for word, freq in word_fd.iteritems():
pos_score = BigramAssocMeasures.chi_sq(label_word_fd['pos'][word],
(freq, pos_word_count), total_word_count)
neg_score = BigramAssocMeasures.chi_sq(label_word_fd['neg'][word],
(freq, neg_word_count), total_word_count)
wordScores[word] = pos_score + neg_score
termScore = sorted(wordScores.items(),key=lambda(w,s):s,reverse=True)[:size]
self.terms = [w for (w,s) in termScore];
def __setTermsSWNSS__(self,size):
sentiScore = self.__getSentiWords__();
wordScores = {}
for word in self.reader.words():
try:
score = sentiScore[word];
except KeyError, e:
score = 0;
#try:
# count = wordScores[word];
#except KeyError, e:
# count = 0;
#wordScores[word] = score + count;
wordScores[word] = score
# del sentiScore
termScore = sorted(wordScores.items(),key=lambda(w,s):s,reverse=True)[:size]
self.terms = [w for (w,s) in termScore];
def __getSentiWords__(self,location=config.SENTI_WORDNET_FILE):
from sentiwordnet import SentiWordNetCorpusReader, SentiSynset
swn = SentiWordNetCorpusReader(location)
w = {}
for senti_synset in swn.all_senti_synsets():
score = senti_synset.pos_score + senti_synset.neg_score
#if totalScore > 0 :
# score = abs(senti_synset.pos_score-senti_synset.neg_score)/totalScore
#else :
# continue;
if score > 0 :
word = senti_synset.synset.name.split('.')[0]
try:
if w[word]>=score:
continue;
except KeyError, e:
pass
w[word] = score
return w;
def __del__(self):
pass
class SpecialTokenizer(RegexpTokenizer):
"""
Tokenizer for Adding the tag NOT_ to every word
between a negation word and the first punctuation mark following
the negation word
Super Class : nltk.tokenize.regexp.RegexpTokenizer
"""
def __init__(self, pattern=r'\w+|[^\w\s]+'):
super(SpecialTokenizer, self).__init__(pattern)
def tokenize(self, text):
tok = super(SpecialTokenizer,self).tokenize(text)
try:
ind = tok.index('not')
except Exception, e:
return tok
tok.remove('not')
for (i,s) in enumerate(tok[ind:]):
if re.match("^[A-Za-z0-9]*$",s):
tok[ind + i] = 'NOT_'+s
return tok
class SpecialPolarityDataReader(PolarityDataReader):
"""
SpecialPolarityDataReader uses Special Tokenizer
for adding the tag NOT_ to every word between a
negation word and the first punctuation mark following
the negation word
Super Class : PolarityDataReader
"""
def __init__(self, rootLocation = config.POLARITY_DATASET):
reader = Reader(rootLocation,r'.*/.*', cat_pattern=r'(.*)/.*',
word_tokenizer = SpecialTokenizer())
super(SpecialPolarityDataReader, self).__init__(reader=reader)
def inc(wordDict,word):
try:
wordDict[word] +=1;
except KeyError, e:
wordDict[word] =1;