I have a directory of 1,000 files. Each file has many lines where each line is an ngram varying from 4 - 8 bytes. I'm trying to parse all files to get the distinct ngrams as a header row, then for each file, I want to write a row that has the frequency of that ngram sequence occurring within the file.
The following code made it through gathering the headers, but hit a memory error when trying to write the headers to the csv file. I was running it on an Amazon EC2 instance with 30GB of RAM. Can anyone provide recommendations for optimizations of which I'm unaware?
#Note: A combination of a list and a set is used to maintain order of metadata
#but still get performance since non-meta headers do not need to maintain order
header_list = []
header_set = set()
header_list.extend(META_LIST)
for ngram_dir in NGRAM_DIRS:
ngram_files = os.listdir(ngram_dir)
for ngram_file in ngram_files:
with open(ngram_dir+ngram_file, 'r') as file:
for line in file:
if not '.' in line and line.rstrip('\n') not in IGNORE_LIST:
header_set.add(line.rstrip('\n'))
header_list.extend(header_set)#MEMORY ERROR OCCURRED HERE
outfile = open(MODEL_DIR+MODEL_FILE_NAME, 'w')
csvwriter = csv.writer(outfile)
csvwriter.writerow(header_list)
#Convert ngram representations to vector model of frequencies
for ngram_dir in NGRAM_DIRS:
ngram_files = os.listdir(ngram_dir)
for ngram_file in ngram_files:
with open(ngram_dir+ngram_file, 'r') as file:
write_list = []
linecount = 0
header_dict = collections.OrderedDict.fromkeys(header_set, 0)
while linecount < META_FIELDS: #META_FIELDS = 3
line = file.readline()
write_list.append(line.rstrip('\n'))
linecount += 1
file_counter = collections.Counter(line.rstrip('\n') for line in file)
header_dict.update(file_counter)
for value in header_dict.itervalues():
write_list.append(value)
csvwriter.writerow(write_list)
outfile.close()