-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathinventory.py
More file actions
67 lines (63 loc) · 2.22 KB
/
Copy pathinventory.py
File metadata and controls
67 lines (63 loc) · 2.22 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
from nltk_helper import get_nouns, get_nouns_carefully, get_similar_nouns
import nltk
import mycommands
import random
import numpy as np
class Inventory:
noun_bonus = 5
commands_limit = 10
unknown_penalty = 100.0
blacklist = {'drop', 'leave', 'throw', 'off'}
def __init__(self, update_command):
self.text = ''
self.nr = 0
self.nouns = {}
self.content = {}
self.update_command = update_command
self.update()
def get_commands(self, word, k, rep):
if word not in mycommands.commands:
return []
com = mycommands.commands[word]
result = []
for text, nouns, freq in com:
for w in text.split():
if w in self.blacklist:
break
else:
try:
text = text.replace(word, rep)
except UnicodeDecodeError:
pass
score = k ** 2
score *= freq
for n in nouns:
if n != word:
if n in self.content:
(lk, w) = self.content[n]
text = text.replace(n, w)
score *= (lk ** 2) * self.noun_bonus
else:
score /= self.unknown_penalty
if score > 0:
result.append((score, text))
return result
def update(self):
text = self.update_command()
if text != self.text:
self.nr += 1
self.text = text
commands = []
old_content = self.content
nouns = get_nouns_carefully(self.text)
self.content = get_similar_nouns(nouns)
for s, (k, w) in self.content.iteritems():
if s not in old_content:
commands += self.get_commands(s, k, w)
for n in nouns:
if n not in self.nouns:
commands += self.get_commands(n, 1.0, n)
self.nouns = set(nouns)
result = sorted(set(commands), key=lambda (x, _): -x)
return list(reversed([x for (_, x) in result[:self.commands_limit]]))
return []