Middle
# It is necessary to implement a generator that takes two arguments: the filename and the number of words batch_size. # The generator should read the specified file and return batch_size words on each iteration call.
sobes.tech AI
Answer from AI
python def word_batch_generator(filename, batch_size): with open(filename, 'r', encoding='utf-8') as file: batch = [] for line in file: words = line.split() for word in words: batch.append(word) if len(batch) == batch_size: yield batch batch = [] if batch: yield batch
This generator reads a file line by line, splits the lines into words, and collects them into lists of size batch_size. When the desired size is reached, it returns the current batch. At the end, if there are remaining words, it returns them as well.