How can I compress text file by Huffman encoding method by using matlab

5 visualizaciones (últimos 30 días)
To compress the text file
  2 comentarios
dpb
dpb el 10 de Ag. de 2024
huffmanenco is in Communications TB; there are some submissions on File Exchange although it appears all have more or fewer issues from discussions...
Walter Roberson
Walter Roberson el 10 de Ag. de 2024
There have been several postings giving huffman encoding code.

Iniciar sesión para comentar.

Respuestas (1)

Jacob Mathew
Jacob Mathew el 12 de Ag. de 2024
Editada: Jacob Mathew el 12 de Ag. de 2024
Hey Thanishka,
I understand that you want to encode text file using hoffman encoding. You can use the below link to get started on huffman encoding. The documentation also has example code to help you understand the usage of the "huffmanenco" , "huggmandeco" and "huffmandict" function:
To get up and running, you can reference the following code that shows how to read a text file, encode it using Huffman encoding and then decode it.
Note that string values cannot directly be encoded ad hence we are going to convert them to double first:
function huffman_encoding(inputFile, outputFile)
% Read the input text file
fileID = fopen(inputFile, 'r');
text = fscanf(fileID, '%c');
fclose(fileID);
% Calculate the frequency of each character
symbols = unique(text);
freq = histc(text, symbols);
% Map characters to numerical values
numSymbols = double(symbols);
% Create Huffman dictionary
[dict, avglen] = huffmandict(numSymbols, freq / sum(freq));
% Encode the text
numText = double(text);
encodedText = huffmanenco(numText, dict);
% Save the encoded text and dictionary to a .mat file
save(outputFile, 'encodedText', 'dict', 'symbols');
disp(['Text has been encoded and saved to ', outputFile]);
end
% Function to decode the Huffman encoded text
function decodedText = huffman_decoding(encodedFile)
% Load the encoded text and dictionary from the .mat file
load(encodedFile, 'encodedText', 'dict', 'symbols');
% Decode the text
numDecodedText = huffmandeco(encodedText, dict);
% Convert numerical values back to characters
decodedText = char(numDecodedText);
end
% Encode the text
huffman_encoding('input.txt', 'encoded.mat');
% Decode the text
decodedText = huffman_decoding('encoded.mat');
disp(decodedText);

Categorías

Más información sobre Large Files and Big Data en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by