57 lines
2.0 KiB
Python
57 lines
2.0 KiB
Python
import lzma
|
|
from nltk.tokenize import word_tokenize
|
|
from nltk import trigrams
|
|
import string
|
|
from collections import defaultdict, Counter
|
|
|
|
|
|
trigrams_list = []
|
|
model = defaultdict(lambda: defaultdict(lambda: 0))
|
|
|
|
|
|
def preprocess(text):
|
|
_text = text.lower().replace('\\n', ' ').strip()
|
|
for character in _text:
|
|
if character not in string.ascii_lowercase + ' ':
|
|
_text = _text.replace(character, '')
|
|
return word_tokenize(_text)
|
|
|
|
|
|
def predict(word_before, word_after):
|
|
prob_list = list(model[(word_before, word_after)].items())
|
|
print(prob_list)
|
|
max_prob = max(prob_list, key=lambda pair: pair[1], default=('', 0.0))
|
|
if max_prob[1] == 0:
|
|
return 'the'
|
|
return max_prob[0]
|
|
|
|
|
|
with open('train/in.tsv', 'w', encoding='utf-8') as file:
|
|
text = lzma.open('train/in.tsv.xz').read().decode('utf-8')
|
|
file.write(text)
|
|
|
|
with open('train/in.tsv', encoding='utf-8') as file_in, open('train/expected.tsv', encoding='utf-8') as file_expected:
|
|
for index, (line_in, expected) in enumerate(zip(file_in, file_expected)):
|
|
if index % 1000 == 0:
|
|
print(index)
|
|
_, _, _, _, _, _, before, after = line_in.split('\t')
|
|
before, expected, after = preprocess(before), preprocess(expected), preprocess(after)
|
|
words = before + expected + after
|
|
trigrams_list += trigrams(words, pad_right=True, pad_left=True)
|
|
|
|
for trigram in trigrams_list:
|
|
if not trigram[0] or not trigram[1] or not trigram[2]:
|
|
continue
|
|
model[(trigram[0], trigram[2])][trigram[1]] += 1
|
|
|
|
for words_1_3 in model:
|
|
count = sum(model[words_1_3].values())
|
|
for word_2 in model[words_1_3]:
|
|
model[words_1_3][word_2] /= float(count)
|
|
|
|
with open('test-A/in.tsv', encoding='utf-8') as file_in, open('test-A/out.tsv', 'w', encoding='utf-8') as file_out:
|
|
for line_in in file_in:
|
|
_, _, _, _, _, _, before, after = line_in.split('\t')
|
|
word_before_in, word_after_in = preprocess(before)[-1], preprocess(after)[0]
|
|
file_out.write(predict(word_before_in, word_after_in) + '\n')
|