-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathsearch.py
87 lines (70 loc) · 2.37 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
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
import random
from pattern.search import Pattern, STRICT, search
from pattern.en import parsetree, wordnet
def re_search(text, search_string, strict=False):
tree = parsetree(text, lemmata=True)
if strict:
results = search(search_string, tree, STRICT)
else:
results = search(search_string, tree)
return results
def search_out(text, search_string, strict=False):
results = re_search(text, search_string, strict)
output = []
for match in results:
sent = []
for word in match:
sent.append(word.string)
output.append(" ".join(sent))
return output
def contains(text, search_string):
results = re_search(text, search_string)
return len(results) > 0
def hypernym_search(text, search_word):
output = []
synset = wordnet.synsets(search_word)[0]
pos = synset.pos
possible_words = re_search(text, pos)
for match in possible_words:
word = match[0].string
synsets = wordnet.synsets(word)
if len(synsets) > 0:
hypernyms = synsets[0].hypernyms(recursive=True)
if any(search_word == h.senses[0] for h in hypernyms):
output.append(word)
return set(output)
def hypernym_combo(text, category, search_pattern):
possibilities = search_out(text, search_pattern)
output = []
for p in possibilities:
if len(hypernym_search(p, category)) > 0:
output.append(p)
return output
def list_hypernyms(search_word):
output = []
for synset in wordnet.synsets(search_word):
hypernyms = synset.hypernyms(recursive=True)
output.append([h.senses[0] for h in hypernyms])
return output
def random_hyponym(word):
to_return = ''
hyponyms = list_hyponyms(word)
if len(hyponyms) > 0:
to_return = random.choice(hyponyms)
return to_return
def list_hyponyms(word):
output = []
synsets = wordnet.synsets(word)
if len(synsets) > 0:
hyponyms = synsets[0].hyponyms(recursive=True)
output = [h.senses[0] for h in hyponyms]
return output
if __name__ == '__main__':
import sys
#results = list_hypernyms(sys.argv[1])
text = sys.stdin.read()
#results = search_out(text, sys.argv[1], True)
#results = hypernym_search(text, sys.argv[1])
results = hypernym_combo(text, sys.argv[1], sys.argv[2])
for result in set(results):
print result