Tokenizes a text file.
(self, path)
| 32 | self.test = self.tokenize(os.path.join(path, 'test.txt')) |
| 33 | |
| 34 | def tokenize(self, path): |
| 35 | """Tokenizes a text file.""" |
| 36 | assert os.path.exists(path) |
| 37 | # Add words to the dictionary |
| 38 | with open(path, 'r', encoding='utf-8') as f: |
| 39 | tokens = 0 |
| 40 | for line in f: |
| 41 | words = line.split() + ['<eos>'] |
| 42 | tokens += len(words) |
| 43 | for word in words: |
| 44 | self.dictionary.add_word(word) |
| 45 | |
| 46 | # Tokenize file content |
| 47 | with open(path, 'r', encoding='utf-8') as f: |
| 48 | ids = torch.LongTensor(tokens) |
| 49 | token = 0 |
| 50 | for line in f: |
| 51 | words = line.split() + ['<eos>'] |
| 52 | for word in words: |
| 53 | ids[token] = self.dictionary.word2idx[word] |
| 54 | token += 1 |
| 55 | |
| 56 | return ids |
| 57 | |
| 58 | class SentCorpus(object): |
| 59 | def __init__(self, path): |