-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsentence_weighing.py
57 lines (42 loc) · 1.67 KB
/
sentence_weighing.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
import sys
import operator
import math
import nltk
from nltk.tokenize import sent_tokenize, word_tokenize
from util.preprocessor import Preprocessor
from util.word_counter import WordCounter
from util.distance import editDistance
class SentenceScoreCalculator:
def __init__(self, p):
self.sCount = p.sCount
self.counter = WordCounter(p.sCount).count(p.processed)
self.vocabulary = self.counter.wordDict.keys()
self.nWords = len(self.vocabulary)
self.sentences = p.sentences
self.calcuateEditDistance()
def calcuateEditDistance(self):
self.lsw = { }
for s in range(self.sCount):
maxLen = lambda s2: max(len(self.sentences[s]), len(self.sentences[s2]))
ed = lambda s2: editDistance(self.sentences[s], self.sentences[s2])
lsw = lambda s2: float(maxLen(s2) - ed(s2)) / maxLen(s2)
self.lsw[s] = sum(map(lsw, range(self.sCount)))
def sentenceWeight(self, index):
words = self.counter.wordsIn(index)
additionalOccurances = lambda w: ( self.counter.fetchWordCount(w) - self.counter.fetchSentenceWordCount(index, w) )
return reduce(lambda s, w: additionalOccurances(w) / self.nWords, words, 0)
def rank(self, index):
return(self.sentenceWeight(index) + self.lsw[index])
def generateSummary(PATH, SIZE):
p = Preprocessor(PATH, 1).parse()
scorer = SentenceScoreCalculator(p)
summary = sorted(
sorted(
range(p.sCount), key=lambda s: scorer.rank(s), reverse=True)[0:SIZE])
return map(lambda s: p.sentences[s], summary)
if __name__ == "__main__":
PATH = sys.argv[1]
SIZE = int(sys.argv[2]) if len(sys.argv) > 2 else 3
# Print summary
for s in generateSummary(PATH, SIZE):
print s