The code snippet you provided is used to create a vocabulary file from a list of preprocessed texts (after splitting them into words) and to create another file in a specific format where each line represents a text with the frequency of each word occurring in it.
The unoptimized part of your code is the inner loop in the second with open block, where you're looking up the index of each word in wordsList and counting the number of times each word appears in text. The list.index() method is O(n) and is called for every word in each text, and list.count() is also O(n), which results in a very inefficient process when dealing with large datasets.
Here's an optimized version of the code:
# Assuming df["text_processed"] has already been defined
# Split texts into words and create a set to hold unique words
unique_words = set()
for text in df["text_processed"]:
unique_words.update(text.split())
# Convert the set to a list to fix the order of the words
wordsList = list(unique_words)
print(len(wordsList))
# Create a mapping from word to its index to optimize lookup
word_to_index = {word: idx for idx, word in enumerate(wordsList)}
# Write the vocabulary to a file
with open("./new_ap/vocab.txt", "w") as f:
for word in wordsList:
f.write(word + "\n")
# Write the document-word frequency data to a file
with open("./new_ap/ap.dat", "w") as f:
for text in df["text_processed"]:
words = text.split()
word_freq = {}
for word in words:
index = word_to_index[word] # O(1) lookup time
if index in word_freq:
word_freq[index] += 1
else:
word_freq[index] = 1
# Write the number of unique words and their frequencies
f.write(str(len(word_freq)) + " ")
for index, freq in word_freq.items():
f.write(str(index) + ":" + str(freq) + " ")
f.write("\n")
In this optimized version, we first create a dictionary word_to_index that maps each word to its index, which provides O(1) lookup time when we want to find the index of a word. Then we use a dictionary word_freq to keep track of the frequencies of each word in a text, avoiding the need to call text.count(word) which is expensive in terms of time complexity. This should significantly reduce the execution time for large datasets.