If you are experiencing slow import times due to the module loading large unigram/bigram text files, you can optimize the loading process by separating the keys (words) and values (counts) into two distinct files: a text file for words and a binary file for counts.
1. Convert text files to optimized formats
Convert the standard tab-separated text files into a newline-separated ASCII file for words and a binary file for double-precision floating-point counts using the array module.
2. Fast loading implementation
Use str.split for the words and array.fromfile for the binary counts to achieve significantly faster loading compared to standard line-by-line parsing.
Note: This approach changes the data format, making the files harder to inspect with standard tools like grep.
from itertools import izip as zip
from array import array
# Optimized loading pattern
with open('words.txt', 'rb') as lines, open('counts.bin', 'rb') as counts:
words = lines.read().split('\n')
values = array('d')
values.fromfile(counts, 333333) # Replace 333333 with actual count
result_dict = dict(zip(words, values))