-
Notifications
You must be signed in to change notification settings - Fork 29
/
simpleQueryAnswering.py
174 lines (141 loc) · 4.97 KB
/
simpleQueryAnswering.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
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
import sys
import numpy
from corenlp import *
import nltk
import nltk.data
import collections
import yesno
import json
from bs4 import BeautifulSoup
# Setup
corenlp = StanfordCoreNLP()
sent_detector = nltk.data.load("tokenizers/punkt/english.pickle")
# Hardcoded word lists
yesnowords = ["can", "could", "would", "is", "does", "has", "was", "were", "had", "have", "did", "are", "will"]
commonwords = ["the", "a", "an", "is", "are", "were", "."]
questionwords = ["who", "what", "where", "when", "why", "how", "whose", "which", "whom"]
# Take in a tokenized question and return the question type and body
def processquestion(qwords):
# Find "question word" (what, who, where, etc.)
questionword = ""
qidx = -1
for (idx, word) in enumerate(qwords):
if word.lower() in questionwords:
questionword = word.lower()
qidx = idx
break
elif word.lower() in yesnowords:
return ("YESNO", qwords)
if qidx < 0:
return ("MISC", qwords)
if qidx > len(qwords) - 3:
target = qwords[:qidx]
else:
target = qwords[qidx+1:]
type = "MISC"
# Determine question type
if questionword in ["who", "whose", "whom"]:
type = "PERSON"
elif questionword == "where":
type = "PLACE"
elif questionword == "when":
type = "TIME"
elif questionword == "how":
if target[0] in ["few", "little", "much", "many"]:
type = "QUANTITY"
target = target[1:]
elif target[0] in ["young", "old", "long"]:
type = "TIME"
target = target[1:]
# Trim possible extra helper verb
if questionword == "which":
target = target[1:]
if target[0] in yesnowords:
target = target[1:]
# Return question data
return (type, target)
# Get command line arguments
articlefilename = sys.argv[1]
questionsfilename = sys.argv[2]
# Process article file
article = open(articlefilename, 'r')
article = BeautifulSoup(article).get_text()
article = ''.join([i if ord(i) < 128 else ' ' for i in article])
article = article.replace("\n", " . ")
article = sent_detector.tokenize(article)
# Process questions file
questions = open(questionsfilename, 'r').read()
questions = questions.decode('utf-8')
questions = questions.splitlines()
# Iterate through all questions
for question in questions:
# Answer not yet found
done = False
# Tokenize question
print question
qwords = nltk.word_tokenize(question.replace('?', ''))
questionPOS = nltk.pos_tag(qwords)
# Process question
(type, target) = processquestion(qwords)
# Answer yes/no questions
if type == "YESNO":
yesno.answeryesno(article, qwords)
continue
# Get sentence keywords
searchwords = set(target).difference(commonwords)
dict = collections.Counter()
# Find most relevant sentences
for (i, sent) in enumerate(article):
sentwords = nltk.word_tokenize(sent)
wordmatches = set(filter(set(searchwords).__contains__, sentwords))
dict[sent] = len(wordmatches)
# Focus on 10 most relevant sentences
for (sentence, matches) in dict.most_common(10):
parse = json.loads(corenlp.parse(sentence))
sentencePOS = nltk.pos_tag(nltk.word_tokenize(sentence))
# Attempt to find matching substrings
searchstring = ' '.join(target)
if searchstring in sentence:
startidx = sentence.index(target[0])
endidx = sentence.index(target[-1])
answer = sentence[:startidx]
done = True
# Check if solution is found
if done:
continue
# Check by question type
answer = ""
for worddata in parse["sentences"][0]["words"]:
# Mentioned in the question
if worddata[0] in searchwords:
continue
if type == "PERSON":
if worddata[1]["NamedEntityTag"] == "PERSON":
answer = answer + " " + worddata[0]
done = True
elif done:
break
if type == "PLACE":
if worddata[1]["NamedEntityTag"] == "LOCATION":
answer = answer + " " + worddata[0]
done = True
elif done:
break
if type == "QUANTITY":
if worddata[1]["NamedEntityTag"] == "NUMBER":
answer = answer + " " + worddata[0]
done = True
elif done:
break
if type == "TIME":
if worddata[1]["NamedEntityTag"] == "NUMBER":
answer = answer + " " + worddata[0]
done = True
elif done:
answer = answer + " " + worddata[0]
break
if done:
print answer
if not done:
(answer, matches) = dict.most_common(1)[0]
print answer