-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibGeneral.py
More file actions
419 lines (333 loc) · 11.6 KB
/
libGeneral.py
File metadata and controls
419 lines (333 loc) · 11.6 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
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
#! /usr/bin/python
# -*- coding: utf-8 -*-
import re
import os
import sys
import sqlite3
import operator
import extractor
import codecs
import math
'''
Removes special characters like '\n', '\s' etc from a given string
INPUT:
s: the string to remove the characters from
OUTPUT:
s: the string without special characters
'''
def removeSpecialCharacters(s):
# Remove all characters except for the given ones
uRet = re.sub(u'[^A-Za-z äüÖÄÜßêéèáíóúñ]+', ' ', s)
return uRet
'''
Removes additional spaces in a string
The returned string only has single spaces
'''
def removeAdditionalSpaces(s):
return re.sub('[ +]+', ' ', s)
'''
Makes a given string all lower case with special german characters
'''
def makeStringLowerCase(s):
s = s.lower()
s = s.replace(u'Ü', u'ü')
s = s.replace(u'Ä', u'ä')
s = s.replace(u'Ö', u'ö')
return s
'''
Creates the database needed for the task.
If database already exists, it will be deleted!
'''
def createSQLiteDB(db):
# Remove old database
if os.path.isfile(db):
os.remove(db)
db_connection = sqlite3.connect(db)
db_connection.execute('''CREATE TABLE TRAINING
(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
WORD_VECTOR TEXT,
CLASS TEXT NOT NULL,
FILENAME TEXT,
FOR_TESTING INTEGER
);''')
db_connection.close()
'''
Make a csv string from a localDictionary
key;value
Lines are separated by '\n'
'''
def makeStringFromDictionary(localDictionary):
outputString = u""
for key in localDictionary.keys():
if outputString == "":
outputString = key + u";" + unicode(localDictionary[key])
else:
outputString = outputString + u"\n" + key + u";" + unicode(localDictionary[key])
return outputString
def makeDictionaryFromString(dicString):
outputDict = {}
dicList = dicString.split("\n")
for line in dicList:
if line == "":
continue
splitLine = line.split(";")
try:
key = splitLine[0]
value = splitLine[1]
except:
print "ERROR IN LINE: " + line
sys.exit()
if value == "":
continue
outputDict[key] = float(value)
return outputDict
'''
Calculates the sum of all values in the localDictionary
'''
def getDictionarySum(localDictionary):
sum = 0.0
for key in localDictionary.keys():
sum += localDictionary[key]
return sum
'''
Calculates the sum of all values and divides every value with that sum.
Returns the normalized localDictionary.
'''
def normalizeDictionary(localDictionary):
sum = getDictionarySum(localDictionary)
for key in localDictionary.keys():
localDictionary[key] = localDictionary[key] / sum
return localDictionary
'''
Returns a localDictionary with the n keys with highest value
INPUT:
localDictionary - the localDictionary to get the values from
n - the n highest values that should be returned
OUTPUT:
outputDictionary - a localDictionary containing the n highest values
'''
def getHighestValues(localDictionary, n):
outputDictionary = {}
sorted_keywords = sorted(localDictionary.iteritems(), key=operator.itemgetter(1), reverse=True)
dicLen = len(sorted_keywords)
if n > dicLen:
n = dicLen
x = 0
while x < n:
key = sorted_keywords[x]
outputDictionary[key[0]] = localDictionary[key[0]]
x += 1
return outputDictionary
def getLowestValues(localDictionary, n):
outputDictionary = {}
sorted_keywords = sorted(localDictionary.iteritems(), key=operator.itemgetter(1), reverse=False)
dicLen = len(sorted_keywords)
if n > dicLen:
n = dicLen
x = 0
while x < n:
key = sorted_keywords[x]
outputDictionary[key[0]] = localDictionary[key[0]]
x += 1
return outputDictionary
def createWordVector(absFilename):
inputFile = codecs.open(absFilename, "r", "utf-8")
inputString = inputFile.read()
# Get the wordlist, remove stopwords and stem the words
inputString = removeSpecialCharacters(inputString)
inputString = removeAdditionalSpaces(inputString)
inputString = makeStringLowerCase(inputString)
wordList = inputString.split()
wordList = removeSingleCharacters(wordList)
wordList = extractor.removeStopwords(wordList, "english")
wordList = extractor.removeStopwords(wordList, "all_names")
wordList = extractor.stemList(wordList)
wordVector = makeDictionaryFromList(wordList)
return wordVector
'''
Reads a given html file to the DB
'''
def readFileToDB(filename, path, connection, docClass, forTesting):
cursor = connection.cursor()
filename = unicode(filename)
absFilename = path + filename
wordVector = createWordVector(absFilename)
# If the word list is empty
# Dont write list to Database
if len(wordVector.keys()) == 0:
print "ERROR reading file : " + absFilename
return
# Write data to database
serializedDictionary = makeStringFromDictionary(wordVector)
values = (serializedDictionary, docClass, filename, forTesting)
sql = "INSERT INTO TRAINING (WORD_VECTOR, CLASS, FILENAME, FOR_TESTING) VALUES (?,?,?,?);"
cursor.execute(sql, values)
'''
Calculate the global dictionary from all files in DB
'''
def calculateIDFVector(connection, docClass):
values = [docClass,]
sql = "SELECT WORD_VECTOR FROM TRAINING WHERE CLASS = ?;"
selectCursor = connection.execute(sql, values)
idfVector = {}
rows = selectCursor.fetchall()
for row in rows:
#url = row[0]
serializedDictionary = row[0]
#docClass = row[3]
#idD = row[4]
loadedDictionary = makeDictionaryFromString(serializedDictionary)
for key in loadedDictionary:
if not key in idfVector.keys():
idfVector[key] = 1.0
else:
idfVector[key] += 1.0
for key in idfVector:
rowLength = len(rows)
idfVector[key] = math.log(float(rowLength)/idfVector[key],10)
return idfVector
'''
Max value from dictionary
'''
def getMaxValueFromDictionary(dictionary):
try:
b = dict(map(lambda item: (item[1],item[0]),dictionary.items()))
keys = b.keys()
maxValue = max(keys)
return maxValue
except:
return 0.0
def getKeyFromMaxValueFromDictionary(dictionary):
try:
b = dict(map(lambda item: (item[1],item[0]),dictionary.items()))
keys = b.keys()
maxValue = max(keys)
key = b[maxValue]
return key
except:
return ""
'''
Creates a global index dictionary from a given database connection
OUTPUT:
key=word:value=index
'''
def createGlobalIndexDictionary(connection):
indexDict = {}
index = 1
sql = "SELECT * FROM TRAINING WHERE 1;"
selectCursor = connection.execute(sql)
rows = selectCursor.fetchall()
for row in rows:
serializedDictionary = row[1]
loadedDictionary = {}
loadedDictionary = makeDictionaryFromString(serializedDictionary)
for key in loadedDictionary:
if not key in indexDict.keys():
indexDict[key] = index
index += 1
return indexDict
'''
Writes the given dictionary to specified file
INPUT:
dictionary - the dictionary containing key and value. Note that key should be UTF-8 encoded
fileName - the filename to write the dictionary to the disk to. The file will be saved in current working directory
'''
def writeDictionaryToDisk(dictionary, fileName):
# save the results to file named results_"document_filename".txt
outputFile = codecs.open(fileName, 'w', encoding="utf-8")
sorted_keywords = sorted(dictionary.iteritems(), key=operator.itemgetter(1))
for word_tuple in sorted_keywords:
line = word_tuple[0] + ";" + unicode(dictionary[word_tuple[0]]) +'\n'
outputFile.write(line)
outputFile.close()
'''
Reads the given file into a dictionary
INPUT:
fileName - the filename to read from
'''
def readDictionaryFromDisk(fileName):
inputFile = codecs.open(fileName, 'r', encoding="utf-8")
string = inputFile.read()
return makeDictionaryFromString(string)
'''
Updates the database by filtering the n most common words
'''
def updateMostCommonWords(DATABASE_NAME, docClass, n, testing=0):
connection = sqlite3.connect(DATABASE_NAME)
values = [docClass,]
sql = "SELECT * FROM TRAINING WHERE CLASS = ?;"
selectCursor = connection.execute(sql, values)
rows = selectCursor.fetchall()
mostCommonWordsDictionary = {}
for row in rows:
originalWordVectorString = row[5]
originalWordVector = makeDictionaryFromString(originalWordVectorString)
for key in originalWordVector.keys():
if not key in mostCommonWordsDictionary.keys():
mostCommonWordsDictionary[key] = originalWordVector[key]
else:
mostCommonWordsDictionary[key] += originalWordVector[key]
mostCommonWordsDictionary = getHighestValues(mostCommonWordsDictionary, n)
print mostCommonWordsDictionary
for row in rows:
idD = row[4]
originalWordVectorString = row[5]
originalWordVector = makeDictionaryFromString(originalWordVectorString)
newWordVector = {}
for key in originalWordVector.keys():
if key in mostCommonWordsDictionary.keys():
newWordVector[key] = originalWordVector[key]
if len(newWordVector) == 0:
pass
if(testing):
newWordVector = originalWordVector
newWordVectorString = makeStringFromDictionary(newWordVector)
values = (newWordVectorString, idD)
sql = "UPDATE TRAINING SET WORD_VECTOR = ? WHERE ID = ?"
connection.execute(sql, values)
#connection.commit()
connection.commit()
'''
Removes single characters from a given list
'''
def removeSingleCharacters(wordList):
for word in wordList:
if len(word) == 1:
wordList.remove(word)
return wordList
def makeDictionaryFromList(wordList):
dictionary = {}
for word in wordList:
if word not in dictionary.keys():
dictionary[word] = 1.0
else:
dictionary[word] += 1.0
return dictionary
def determineClasses(connection):
classes = []
cursor = connection.cursor()
sql = "SELECT DISTINCT CLASS FROM TRAINING;"
cursor.execute(sql)
for row in cursor.fetchall():
className = row[0]
classes.append(className)
return classes
def calculateTfIdfVector(dictionary, connection, className):
idf_vector = calculateIDFVector(connection, className)
maximumValue = getMaxValueFromDictionary(dictionary)
tf_idf_dictionary = {}
for key in dictionary:
tf_idf_dictionary[key] = float(dictionary[key]/maximumValue) * float(idf_vector[key])
return tf_idf_dictionary
def calculateAPrioriDictionary(connection):
cursor = connection.cursor()
sql = "SELECT CLASS, COUNT(CLASS) FROM TRAINING GROUP BY CLASS;"
cursor.execute(sql)
aPrioriDict = {}
for row in cursor.fetchall():
className = row[0]
freq = row[1]
aPrioriDict[className] = freq
aPrioriDict = normalizeDictionary(aPrioriDict)
return aPrioriDict