1

我正在尝试使用来自http://www.explainth.at/downloads/huff.zip的霍夫曼算法

单元中有两个功能:

函数压缩(ASource:TMemoryStream):TMemoryStream;
函数解压缩(ASource:TMemoryStream):TMemoryStream;

我已经成功地将文件中的每一行压缩到另一个文件中。

function StreamToString(const stream: TStream) : string;
var
Size: Integer;
begin
  result:='';
  Size := Stream.Size - Stream.Position;
  SetString(result, nil, Size);
  Stream.Read(Pointer(result)^, Size);
end;
procedure TMaster.Button1Click(Sender: TObject);
var
list,list_:TStringlist;
AStream:TMemoryStream;
BStream:TMemoryStream;
s:string;
i,j:integer;
begin
  list := TStringList.Create;
  list_:= TStringList.Create;
  list.LoadFromFile('d:\input.txt');

  for j := 0 to List.Count - 1 do
  begin
    s:=list[j];
    if (Length(s) = 0) then exit;
    {i:=Pos(#13#10,s);
    while (i > 0) do
    begin
      Delete(s,i,2);
      i:=Pos(#13#10,s);
    end;}

    AStream:=TMemoryStream.Create;
    with AStream do WriteBuffer(s[1],Length(s));
    with THuffman.Create do
    try
      BStream:=Compress(AStream);
    finally
      Free;
      AStream.Free;
    end;

  with THuffman.Create do
  try
    AStream:=ProcessToDecrypt (BStream);
    list_.Add(StreamToString(BStream));
  finally
    BStream.Free;
  end
  end; //for j := 0 to List.Count - 1 do

  list_.SaveToFile('d:\output.txt');
  list_.free;
  list.free; 
end;

function THuffman.ProcessToDecrypt(ASource:TMemoryStream):TMemoryStream;
var ASize:Integer;
begin
  ASize:=ReBuildTree(ASource);
  exit;
end;

我还想将每个压缩行从文件解压缩为字符串。

这是我为解压缩字符串所做的工作

procedure TMaster.Button2Click(Sender: TObject);
var i:Integer;
    AText:String;
    AStream:TMemoryStream;
    BStream:TMemoryStream;
begin
  AText:='È1ëz-';
  BStream:=TMemoryStream.Create;

  with BStream do WriteBuffer(AText[1],Length(AText));

  with THuffman.Create do
  try
    AStream:=ProcessToDecrypt (BStream);
    AStream:=Decompress(BStream); 
    memoOut.Lines.add.StreamToString(BStream);
  finally
    BStream.Free;
  end;
end;

Button2Click 过程不起作用。简短的问题是如何解压缩压缩字符串

DeCompress的参数是TMemoryStream,如何使用字符串作为参数?
如何将 DeCompress 的输出设为字符串?

4

1 回答 1

2

除了我上面的评论,只看你的代码, AText 中的值可能不是压缩字符串的正确表示。以下非常简单的程序(基于您的)有效:

uses Huffman;

procedure TForm1.UncompressButtonClick(Sender: TObject);
var
  AStream:TMemoryStream;
  BStream:TMemoryStream;
begin
  BStream:=TMemoryStream.Create;
  with BStream do LoadFromFile('c:\temp\in.txt');

  with THuffman.Create do
  try
    AStream:=Decompress(BStream);
    AStream.SaveToFile('c:\temp\out.txt');
  finally
    BStream.Free;
  end;
end;

procedure TForm1.CompressButtonClick(Sender: TObject);
var
  AText:String;
  AStream:TMemoryStream;
  BStream:TMemoryStream;
begin
  AText := Edit1.Text;
  BStream:=TMemoryStream.Create;
  with BStream do WriteBuffer(AText[1],Length(AText));
  with THuffman.Create do
  try
    AStream:=Compress(BStream);
    AStream.SaveToFile('c:\temp\in.txt');
  finally
    BStream.Free;
  end;
end;
于 2010-11-26T13:41:10.407 回答