-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.py
201 lines (172 loc) · 5.97 KB
/
parser.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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import pdb
# classes:
class PartOfSpeech(object):
name = ""
abbreviation = ""
elements = []
class Phrase(object):
name = ""
abbreviation = ""
rules = []
class State(object):
rule = {}
index = []
class TreeChart(object):
branches = []
# Parts of Speech - Initialization of words:
noun = PartOfSpeech()
noun.name = "noun"
noun.abbreviation = "N"
noun.elements = ["subject", "information"]
properNoun = PartOfSpeech()
properNoun.name = "proper noun"
properNoun.abbreviation = "PN"
properNoun.elements = ["www.upf.edu", "Bea"]
verb = PartOfSpeech()
verb.name = "verb"
verb.abbreviation = "V"
verb.elements = ["can", "am", "read"]
pronoun = PartOfSpeech()
pronoun.name = "pronoun"
pronoun.abbreviation = "P"
pronoun.elements = ["I", "you"]
determiner = PartOfSpeech()
determiner.name = "determiner"
determiner.abbreviation = "DET"
determiner.elements = ["that"]
adjective = PartOfSpeech()
adjective.name = "adjective"
adjective.abbreviation = "ADJ"
adjective.elements = ["familiar"]
adverb = PartOfSpeech()
adverb.name = "adverb"
adverb.abbreviation = "ADV"
adverb.elements = ["further", "Please"]
preposition = PartOfSpeech()
preposition.name = "preposition"
preposition.abbreviation = "PREP"
preposition.elements = ["with", "on"]
# Phrases - Initialization of rules:
prepositionalPhrase = Phrase()
nominalPhrase = Phrase()
adjectivePhrase = Phrase()
verbalPhrase = Phrase()
sentence = Phrase()
prepositionalPhrase.name = "prepositional phrase"
prepositionalPhrase.abbreviation = "PP"
prepositionalPhrase.rules = ["PREP NP"]
nominalPhrase.name = "nominal phrase"
nominalPhrase.abbreviation = "NP"
nominalPhrase.rules = ["PN", "P", "DET N", "ADJP PP"]
adjectivePhrase.name = "adjective phrase"
adjectivePhrase.abbreviation = "ADJP"
adjectivePhrase.rules = ["ADJ", "ADV N"]
verbalPhrase.name = "verbal phrase"
verbalPhrase.abbreviation = "VP"
verbalPhrase.rules = ["P V", "ADV V"]
sentence.name = "sentence"
sentence.abbreviation = "S"
sentence.rules = ["VP NP"]
# other global variables:
allPhrases = [prepositionalPhrase, nominalPhrase, adjectivePhrase, verbalPhrase, sentence]
allTerminals = [noun, verb, preposition, determiner, adjective, adverb, pronoun, properNoun]
globalStateSet = []
placeholderstate = State()
placeholderstate.rule = {"start": "*", "end": "@*"}
placeholderstate.index = [0, 0]
def earley(words):
chart = []
initialState = State()
initialState.rule = {"start": "$", "end": "@S"}
initialState.index = [0, 0]
addtochart(initialState, 0)
for i, word in enumerate(words):
if len(globalStateSet) <= i:
addtochart(placeholderstate, i)
for j, state in enumerate(globalStateSet[i]):
# print "state rule: ", state.rule["start"], "-->", state.rule["end"], i, word, j
if not isTerminal(afterDot(state.rule["end"])) and not afterDot(state.rule["end"]) == "":
print "predicting: ", state.rule["start"], "-->", state.rule["end"]
predictor(state)
elif isTerminal(afterDot(state.rule["end"])):
print "scanning: ", state.rule["start"], "-->", state.rule["end"]
scanner(state, word)
else:
print "completing: ", state.rule["start"], "-->", state.rule["end"]
completer(state) # dot is at the end of rule's right hand side
printChart()
def predictor(state):
predicted = afterDot(state.rule["end"])
predictedPhraseList = [phrase for phrase in allPhrases if phrase.abbreviation == predicted]
if len(predictedPhraseList) > 0:
predictedPhrase = predictedPhraseList[0]
else:
return
currentChartIndex = state.index[-1] # second index
for end in predictedPhrase.rules:
newState = State()
newState.rule = {"start": predicted, "end": " ".join(["@", end])}
newState.index = [currentChartIndex, currentChartIndex]
addtochart(newState, currentChartIndex)
def scanner(state, word):
currentSentenceIndex = state.index[-1] # second index
scanned = afterDot(state.rule["end"])
scannedTerminal = [terminal for terminal in allTerminals if terminal.abbreviation == scanned][0]
if word in scannedTerminal.elements:
print word, " is a ", scannedTerminal.name, "\n"
newState = State()
newState.rule = {"start": scanned, "end": " ".join([word, "@"])}
newState.index = [currentSentenceIndex, currentSentenceIndex+1]
addtochart(newState, currentSentenceIndex+1)
def completer(state):
start = state.rule["start"]
end = state.rule["end"]
j = state.index[0]
k = state.index[-1]
currentChartPart = globalStateSet[j]
relevantStates = [state for state in currentChartPart if (state.index[-1] == j) and (afterDot(state.rule["end"]) == start)]
for state in relevantStates:
# shifting the dot one further:
splitted = state.rule["end"].split("@")
before = splitted[0]
after = splitted[-1]
x = after.split( )
x.insert(1, "@")
newAfter = " ".join(x)
newEnd = " ".join([before, newAfter])
# adding new state to chart:
newState = State()
newState.rule = {"start": state.rule["start"], "end": newEnd}
newState.index = [state.index[0], k]
addtochart(newState, k)
def addtochart(state, index):
if len(globalStateSet) <= index:
globalStateSet.append([state])
elif globalStateSet[index] == [placeholderstate]:
globalStateSet[index] = [state]
elif state not in globalStateSet[index]:
globalStateSet[-1].append(state)
def incomplete(state):
return (afterDot(state.rule["end"]) != "") # True if there is a symbol after the dot
def afterDot(state):
# @ symbolizes the dot
x = state.split("@")[-1]
if x != "":
y = x.split( )[0]
if y != "@":
return y # return the first symbol after the dot
else:
return ""
else:
return ""
def isTerminal(symbol):
x = (symbol in [t.abbreviation for t in allTerminals])
return x
def printChart():
print "\nHere is the chart:\n_____________________\n"
for x in globalStateSet:
for y in x:
print y.index, " ", y.rule["start"], " --> ", y.rule["end"]
inputSentence = input("Which sentence should I parse? ")
inputSentenceAsList = inputSentence.split( )
earley(inputSentenceAsList)