gpt4 book ai didi

delphi - 比较大文件

转载 作者:行者123 更新时间:2023-12-03 15:09:11 25 4
gpt4 key购买 nike

我有一些文件(3-5)需要比较:
文件 1.txt 有 100 万个字符串。
文件2.txt有1000万个字符串。
文件3.txt有500万个字符串。
所有这些文件都与文件keys.txt(10000个字符串)进行比较。如果当前打开的文件中的行与keys.txt中的行之一相同,则将此行写入output.txt(我希望您明白我的意思)。

现在我有:

function Thread.checkKeys(sLine: string): boolean;
var
SR: TStreamReader;
line: string;
begin
Result := false;
SR := TStreamReader.Create(sKeyFile); // sKeyFile - Path to file keys.txt
try
while (not(SR.EndOfStream)) and (not(Result))do
begin
line := SR.ReadLine;
if LowerCase(line) = LowerCase(sLine) then
begin
saveStr(sLine);
inc(iMatch);
Result := true;
end;
end;
finally
SR.Free;
end;
end;

procedure Thread.saveStr(sToSave: string);
var
fOut: TStreamWriter;
begin
fOut := TStreamWriter.Create('output.txt', true, TEncoding.UTF8);
try
fOut.WriteLine(sToSave);
finally
fOut.Free;
end;
end;

procedure Thread.updateFiles;
begin
fmMain.flDone.Caption := IntToStr(iFile);
fmMain.flMatch.Caption := IntToStr(iMatch);
end;

并循环

    fInput := TStreamReader.Create(tsFiles[iCurFile]);
while not(fInput.EndOfStream) do
begin
sInput := fInput.ReadLine;
checkKeys(sInput);
end;
fInput.Free;
iFile := iCurFile + 1;
Synchronize(updateFiles);

所以,如果我将这 3 个文件与文件 key.txt 进行比较,大约需要 4 小时。如何减少比较时间?

最佳答案

一个简单的解决方案是使用关联容器来存储 key 。这可以提供有效的查找。

在Delphi中您可以使用TDictionary<TKey,TValue>来自Generics.Collections 。该容器的实现对键进行哈希处理并提供 O(1) 查找。

像这样声明容器:

Keys: TDictionary<string, Boolean>; 
// doesn't matter what type you use for the value, we pick Boolean since we
// have to pick something

像这样创建并填充它:

Keys := TDictionary<string, Integer>.Create;
SR := TStreamReader.Create(sKeyFile);
try
while not SR.EndOfStream do
Keys.Add(LowerCase(SR.ReadLine), True);
// exception raised if duplicate key found
finally
SR.Free;
end;

那么你的检查函数就变成了:

function Thread.checkKeys(const sLine: string): boolean;
begin
Result := Keys.ContainsKey(LowerCase(sLine));
if Result then
begin
saveStr(sLine);
inc(iMatch);
end;
end;

关于delphi - 比较大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19398140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com