forked from akngs/ecogwiki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.py
53 lines (40 loc) · 1.29 KB
/
search.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
# -*- coding: utf-8 -*-
import re
import operator
from collections import OrderedDict
P_EXP = ur'(?P<sign>[+-])(?P<title>.+?)(?=\s$|\s[+-])'
def parse_expression(exp):
exp = exp.strip() + ' '
positives = []
negatives = []
for m in re.finditer(P_EXP, exp):
sign = m.group('sign')
title = m.group('title')
if sign == '+':
positives.append(title)
else:
negatives.append(title)
return {
'pos': positives,
'neg': negatives,
}
def evaluate(positives, negatives):
scoretable = {}
length = len(positives.keys()) + len(negatives.keys())
# calc positives
for scores in positives.values():
for title, score in scores.items():
if title not in scoretable:
scoretable[title] = 0.0
scoretable[title] += score / length
# calc negatives
for scores in negatives.values():
for title, score in scores.items():
if title not in scoretable:
scoretable[title] = 0.0
scoretable[title] -= score / length
# descending by score
sorted_tuples = sorted(scoretable.iteritems(),
key=operator.itemgetter(1),
reverse=True)
return OrderedDict(sorted_tuples)