Returns - string Input - str: a string of words called sentence ---------- Trains the sentence. It does this by creating a map of current words to next words and their counts for each time the next word appears after the current word - takes i
(self, sentence)
| 64 | ) |
| 65 | |
| 66 | def train(self, sentence): |
| 67 | """ |
| 68 | Returns - string |
| 69 | Input - str: a string of words called sentence |
| 70 | ---------- |
| 71 | Trains the sentence. It does this by creating a map of |
| 72 | current words to next words and their counts for each |
| 73 | time the next word appears after the current word |
| 74 | - takes in the sentence and splits it into a list of words |
| 75 | - retrieves the word map and predictions map |
| 76 | - creates the word map and predictions map together |
| 77 | - saves word map and predictions map to the database |
| 78 | """ |
| 79 | cur = self.conn.cursor() |
| 80 | words_list = sentence.split(" ") |
| 81 | |
| 82 | words_map = cur.execute( |
| 83 | "SELECT value FROM WordMap WHERE name='wordsmap'" |
| 84 | ).fetchone()[0] |
| 85 | words_map = json.loads(words_map) |
| 86 | |
| 87 | predictions = cur.execute( |
| 88 | "SELECT value FROM WordPrediction WHERE name='predictions'" |
| 89 | ).fetchone()[0] |
| 90 | predictions = json.loads(predictions) |
| 91 | |
| 92 | for idx in range(len(words_list) - 1): |
| 93 | curr_word, next_word = words_list[idx], words_list[idx + 1] |
| 94 | if curr_word not in words_map: |
| 95 | words_map[curr_word] = {} |
| 96 | if next_word not in words_map[curr_word]: |
| 97 | words_map[curr_word][next_word] = 1 |
| 98 | else: |
| 99 | words_map[curr_word][next_word] += 1 |
| 100 | |
| 101 | # checking the completion word against the next word |
| 102 | if curr_word not in predictions: |
| 103 | predictions[curr_word] = { |
| 104 | "completion_word": next_word, |
| 105 | "completion_count": 1, |
| 106 | } |
| 107 | else: |
| 108 | if ( |
| 109 | words_map[curr_word][next_word] |
| 110 | > predictions[curr_word]["completion_count"] |
| 111 | ): |
| 112 | predictions[curr_word]["completion_word"] = next_word |
| 113 | predictions[curr_word]["completion_count"] = words_map[curr_word][ |
| 114 | next_word |
| 115 | ] |
| 116 | |
| 117 | words_map = json.dumps(words_map) |
| 118 | predictions = json.dumps(predictions) |
| 119 | |
| 120 | cur.execute( |
| 121 | "UPDATE WordMap SET value = (?) WHERE name='wordsmap'", (words_map,) |
| 122 | ) |
| 123 | cur.execute( |
no outgoing calls
no test coverage detected