| 89 | return s.split() |
| 90 | |
| 91 | def get_wikipedia_data(n_files, n_vocab, by_paragraph=False): |
| 92 | prefix = '../large_files/' |
| 93 | |
| 94 | if not os.path.exists(prefix): |
| 95 | print("Are you sure you've downloaded, converted, and placed the Wikipedia data into the proper folder?") |
| 96 | print("I'm looking for a folder called large_files, adjacent to the class folder, but it does not exist.") |
| 97 | print("Please download the data from https://dumps.wikimedia.org/") |
| 98 | print("Quitting...") |
| 99 | exit() |
| 100 | |
| 101 | input_files = [f for f in os.listdir(prefix) if f.startswith('enwiki') and f.endswith('txt')] |
| 102 | |
| 103 | if len(input_files) == 0: |
| 104 | print("Looks like you don't have any data files, or they're in the wrong location.") |
| 105 | print("Please download the data from https://dumps.wikimedia.org/") |
| 106 | print("Quitting...") |
| 107 | exit() |
| 108 | |
| 109 | # return variables |
| 110 | sentences = [] |
| 111 | word2idx = {'START': 0, 'END': 1} |
| 112 | idx2word = ['START', 'END'] |
| 113 | current_idx = 2 |
| 114 | word_idx_count = {0: float('inf'), 1: float('inf')} |
| 115 | |
| 116 | if n_files is not None: |
| 117 | input_files = input_files[:n_files] |
| 118 | |
| 119 | for f in input_files: |
| 120 | print("reading:", f) |
| 121 | for line in open(prefix + f): |
| 122 | line = line.strip() |
| 123 | # don't count headers, structured data, lists, etc... |
| 124 | if line and line[0] not in ('[', '*', '-', '|', '=', '{', '}'): |
| 125 | if by_paragraph: |
| 126 | sentence_lines = [line] |
| 127 | else: |
| 128 | sentence_lines = line.split('. ') |
| 129 | for sentence in sentence_lines: |
| 130 | tokens = my_tokenizer(sentence) |
| 131 | for t in tokens: |
| 132 | if t not in word2idx: |
| 133 | word2idx[t] = current_idx |
| 134 | idx2word.append(t) |
| 135 | current_idx += 1 |
| 136 | idx = word2idx[t] |
| 137 | word_idx_count[idx] = word_idx_count.get(idx, 0) + 1 |
| 138 | sentence_by_idx = [word2idx[t] for t in tokens] |
| 139 | sentences.append(sentence_by_idx) |
| 140 | |
| 141 | # restrict vocab size |
| 142 | sorted_word_idx_count = sorted(word_idx_count.items(), key=operator.itemgetter(1), reverse=True) |
| 143 | word2idx_small = {} |
| 144 | new_idx = 0 |
| 145 | idx_new_idx_map = {} |
| 146 | for idx, count in sorted_word_idx_count[:n_vocab]: |
| 147 | word = idx2word[idx] |
| 148 | print(word, count) |