Create a Python script and import the necessary libraries.
python
import os
import os.path
import shutil
import glob
import json
import nltk
from nltk.tokenize import sent_tokenize, word_tokenize
from tqdm import tqdm
Define a function to tokenize a single file.
python
def tokenize_file(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
text = f.read()
sentences = sent_tokenize(text)
tokens = []
for sentence in sentences:
words = word_tokenize(sentence.lower())
tokens.extend(words)
return tokens
Define a function to tokenize all files in a folder.
Define a function to calculate the size of tokens.
python
def get_tokens_size(tokens):
return len(tokens)
Define a function to save the sorted tokenized files to a new folder.
python
def save_sorted_files(files, new_folder_path):
if os.path.exists(new_folder_path):
shutil.rmtree(new_folder_path)
os.makedirs(new_folder_path)
for file in files:
shutil.copy2(file['file_path'], os.path.join(new_folder_path, f'{file["file_path"]}.json'))
Call the functions to tokenize the folder, sort the files, calculate the size of tokens, and save the sorted files to a new folder.
python
folder_path = 'path/to/folder'
new_folder_path = 'path/to/new/folder'
tokenized_files = tokenize_folder(folder_path)
sorted_files = sort_files_by_size(tokenized_files)
for file in sorted_files:
file_path = file['file_path']
tokens = file['tokens']
tokens_size = get_tokens_size(tokens)
with open(file_path, 'w') as f:
json.dump({'file_path': file_path, 'tokens': tokens, 'tokens_size': tokens_size}, f)
This script will create a new folder with the sorted tokenized files. The files will be named after their original file paths, but with a .json extension. The tokens_size field will be included in the JSON output to indicate the size of the tokens in each file.