Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 1 class ParserError(Exception):
- 2 pass
- 3
- 4 class Sentence(object):
- 5
- 6 def __init__(self, subject, verb, obj):
- 7 self.subject = subject[1]
- 8 self.verb = verb[1]
- 9 self.object = obj[1]
- 10
- 11 class action_methods(object):
- 12
- 13 def __init__(self, word_list, word_type):
- 14 self.word_list = word_list
- 15 self.word_type = word_type
- 16 self.peek()
- 17 self.match()
- 18 self.skip()
- 19
- 20 def peek(self):
- 21 if word_list:
- 22 word = word_list[0]
- 23 return word[0]
- 24 else:
- 25 return None
- 26
- 27 def match(self, expecting):
- 28 if word_list:
- 29 word = word_list.pop(0)
- 30
- 31 if word[0] == expecting:
- 32 return word
- 33 else:
- 34 return None
- 35 else:
- 36 return None
- 37
- 38 def skip(self):
- 39 while peek(word_list) == word_type:
- 40 match(word_list, word_type)
- 41
- 42 class parse_methods(object):
- 43
- 44 def __init__(self, actions, word_list):
- 45 #TODO fix error with arguments
- 46 self.word_list = word_list
- 47 self.actions = actions
- 41
- 42 class parse_methods(object):
- 43
- 44 def __init__(self, actions, word_list):
- 45 #TODO fix error with arguments
- 46 self.word_list = word_list
- 47 self.actions = actions
- 48 self.parse_verb()
- 49 self.parse_object()
- 50 self.parse_subject()
- 51
- 52 def parse_verb(self):
- 53 self.actions.skip(self.word_list, 'stop')
- 54
- 55 if actions.peek(word_list) == 'verb':
- 56 return self.actions.match(word_list, 'verb')
- 57 else:
- 58 raise ParserError("Expected a verb next.")
- 59
- 60 def parse_object(self):
- 61 actions.skip(word_list, 'stop')
- 62 next_word = actions.peek(word_list)
- 63 if next_word == 'noun':
- 64 return actions.match(word_list, 'noun')
- 65 elif next_word == 'direction':
- 66 return actions.match(word_list, 'direction')
- 67 else:
- 68 raise ParserError("Expected a noun or direction next.")
- 69
- 70 def parse_subject(self):
- 71 actions.skip(word_list, 'stop')
- 72 next_word = actions.peek(word_list)
- 73
- 74 if next_word == 'noun':
- 75 return actions.match(word_list, 'noun')
- 76 elif next_word == 'verb':
- 77 return ('noun', 'player')
- 78 else:
- 79 raise ParserError("Expected a verb next.")
- 80
- 81 def parse_sentence(word_list):
- 82 parser = parse_methods(action_methods(), word_list)
- 83 subj = methods.parse_subject(word_list)
- 84 verb = methods.parse_verb(word_list)
- 85 obj = methods.parse_object(word_list)
- 86
- 87 return Sentence(subj, verb, obj)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement