gpt4 book ai didi

delphi - 替换文件中的字符(更快的方法)

转载 作者:行者123 更新时间:2023-12-03 15:42:48 27 4
gpt4 key购买 nike

我们经常用另一个“好”字符替换文件中不需要的字符。

界面是:

procedure cleanfileASCII2(vfilename: string; vgood: integer; voutfilename: string);

用我们可能会调用的空格替换所有不需要的内容,cleanfileASCII2(original.txt, 32, clean.txt)

问题是这需要相当长的时间。有没有有比所示更好的方法吗?

procedure cleanfileASCII2(vfilename: string; vgood: integer; voutfilename:
string);
var
F1, F2: file of char;
Ch: Char;
tempfilename: string;
i,n,dex: integer;
begin
//original
AssignFile(F1, vfilename);
Reset(F1);
//outputfile
AssignFile(F2,voutfilename);
Rewrite(F2);
while not Eof(F1) do
begin
Read(F1, Ch);
//
n:=ord(ch);
if ((n<32)or(n>127))and (not(n in [10,13])) then
begin // bad char
if vgood<> -1 then
begin
ch:=chr(vgood);
Write(F2, Ch);
end
end
else //good char
Write(F2, Ch);
end;
CloseFile(F2);
CloseFile(F1);
end;

最佳答案

问题与您处理缓冲区的方式有关。内存传输是所有操作中最昂贵的部分。在本例中,您将逐字节查看文件。通过更改为 block 读取或缓冲读取,您将实现速度的巨大提高。请注意,正确的缓冲区大小根据您读取的位置而有所不同。对于网络文件,您会发现由于 TCP/IP 规定的数据包大小,极大的缓冲区可能效率较低。即使对于来自 gigE 的大数据包,这也变得有点模糊,但一如既往,最好的结果是对其进行基准测试。

为了方便起见,我从标准读取转换为文件流。您可以使用 block 读取轻松地完成相同的操作。在本例中,我获取了一个 15MB 的文件并在您的例程中运行它。对本地文件执行该操作花费了 131,478 毫秒。使用 1024 缓冲区时,花费了 258 毫秒。

procedure cleanfileASCII3(vfilename: string; vgood: integer; voutfilename:string);
const bufsize=1023;
var
inFS, outFS:TFileStream;
buffer: array[0..bufsize] of byte;
readSize:integer;
tempfilename: string;
i: integer;
begin
if not FileExists(vFileName) then exit;

inFS:=TFileStream.Create(vFileName,fmOpenRead);
inFS.Position:=0;
outFS:=TFileStream.Create(vOutFileName,fmCreate);
while not (inFS.Position>=inFS.Size) do
begin
readSize:=inFS.Read(buffer,sizeof(buffer));
for I := 0 to readSize-1 do
begin
n:=buffer[i];
if ((n<32)or(n>127)) and (not(n in [10,13])) and (vgood<>-1) then
buffer[i]:=vgood;
end;
outFS.Write(buffer,readSize);
end;
inFS.Free;
outFS.Free;
end;

关于delphi - 替换文件中的字符(更快的方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/921456/

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