gpt4 book ai didi

delphi - 解析平面文本文件

转载 作者:行者123 更新时间:2023-12-03 15:46:43 24 4
gpt4 key购买 nike

我正在开发一个应用程序,我必须将数据从 CSV 文件上传到数据库表中。问题是,我没有 CSV 文件,但有要转换为 CSV 的纯文本文件。另一个问题是,由于该应用程序由具有不同系统的多个客户使用,因此我有不同布局的不同平面文本文件。

我想要实现的是创建一个从特殊文件加载“规则”的应用程序;这些规则将与纯文本文件一起处理,以生成 CSV 文件。从平面文件转换为 CSV 的应用程序是相同的,只是规则集不同。

我怎样才能实现这个目标?您推荐的最佳实践是什么?

最佳答案

这取决于规则的复杂程度。如果唯一不同的输入是列的名称和使用的分隔符,那么这很简单,但如果您还希望能够解析完全不同的格式(例如 XML 等),那么情况就不同了。

我自己会选择为“记录”读取器实现一个基类,该读取器从文件中读取记录并将其输出到数据集或 CSV。然后,您可以实现子类来实现读取不同的源格式。

如果您愿意,您可以为这些格式添加特定规则,这样您就可以创建一个继承自 BaseReader 的通用 XMLReader,但允许配置列名称。但我会从一堆针对您所获得的格式的硬编码阅读器开始,直到更清楚您可能会遇到这些格式的哪些方言。

编辑:根据要求,提供其外观的示例。

注意,这个例子远非理想!它读取自定义格式,将其传输到一个特定的表结构并将其另存为 CSV 文件。您可能想进一步拆分它,以便可以为不同的表结构重用代码。特别是字段定义,您可能希望能够在后代类或工厂类中进行设置。但为了简单起见,我采取了一种更严格的方法,并在一个基类中放置了太多的智能。

基类具有创建内存数据集所需的逻辑(我使用了 TClientDataSet)。它可以“迁移”文件。实际上,这意味着它读取、验证和导出文件。

读取是抽象的,必须在子类中实现。它应该将数据读取到内存数据集中。这允许您在客户端数据集中进行所有必要的验证。这允许您以与数据库/文件格式无关的方式强制执行字段类型和大小,并在需要时进行任何其他检查。

验证和写入是使用数据集中的数据完成的。从源文件解析为数据集的那一刻起,就不再需要了解源文件格式了。

声明:不要忘记使用DB、DBClient

type
TBaseMigrator = class
private
FData: TClientDataset;
protected
function CSVEscape(Str: string): string;
procedure ReadFile(AFileName: string); virtual; abstract;
procedure ValidateData;
procedure SaveData(AFileName: string);
public
constructor Create; virtual;
destructor Destroy; override;

procedure MigrateFile(ASourceFileName, ADestFileName: string); virtual;
end;

实现:

{ TBaseReader }

constructor TBaseMigrator.Create;
begin
inherited Create;
FData := TClientDataSet.Create(nil);
FData.FieldDefs.Add('ID', ftString, 20, True);
FData.FieldDefs.Add('Name', ftString, 60, True);
FData.FieldDefs.Add('Phone', ftString, 15, False);
// Etc
end;

function TBaseMigrator.CSVEscape(Str: string): string;
begin
// Escape the string to a CSV-safe format;
// Todo: Check if this is sufficient!
Result := '"' + StringReplace(Result, '"', '""', [rfReplaceAll]) + '"';
end;

destructor TBaseMigrator.Destroy;
begin
FData.Free;
inherited;
end;

procedure TBaseMigrator.MigrateFile(ASourceFileName, ADestFileName: string);
begin
// Read the file. Descendant classes need to override this method.
ReadFile(ASourceFileName);

// Validation. Implemented in base class.
ValidateData;

// Saving/exporting. For now implemented in base class.
SaveData(ADestFileName);
end;

procedure TBaseMigrator.SaveData(AFileName: string);
var
Output: TFileStream;
Writer: TStreamWriter;
FieldIndex: Integer;
begin
Output := TFileStream.Create(AFileName,fmCreate);
Writer := TStreamWriter.Create(Output);
try

// Write the CSV headers based on the fields in the dataset
for FieldIndex := 0 to FData.FieldCount - 1 do
begin
if FieldIndex > 0 then
Writer.Write(',');
// Column headers are escaped, but this may not be needed, since
// they likely don't contain quotes, commas or line breaks.
Writer.Write(CSVEscape(FData.Fields[FieldIndex].FieldName));
end;
Writer.WriteLine;

// Write each row
FData.First;
while not FData.Eof do
begin

for FieldIndex := 0 to FData.FieldCount - 1 do
begin
if FieldIndex > 0 then
Writer.Write(',');
// Escape each value
Writer.Write(CSVEscape(FData.Fields[FieldIndex].AsString));
end;
Writer.WriteLine;

FData.Next
end;

finally
Writer.Free;
Output.Free;
end;
end;

procedure TBaseMigrator.ValidateData;
begin
FData.First;
while not FData.Eof do
begin
// Validate the current row of FData
FData.Next
end;
end;

示例子类:TIniFileReader,它读取 inifile 部分,就好像它们是数据库记录一样。可以看到,您只需要实现读取文件的逻辑即可。

type
TIniFileReader = class(TBaseMigrator)
public
procedure ReadFile(AFileName: string); override;
end;

{ TIniFileReader }

procedure TIniFileReader.ReadFile(AFileName: string);
var
Source: TMemIniFile;
IDs: TStringList;
ID: string;
i: Integer;
begin
// Initialize an in-memory dataset.
FData.Close; // Be able to migrate multiple files with one instance.
FData.CreateDataSet;

// Parsing a weird custom format, where each section in an inifile is a
// row. Section name is the key, section contains the other fields.
Source := TMemIniFile.Create(AFileName);
IDs := TStringList.Create;
try
Source.ReadSections(IDs);

for i := 0 to IDs.Count - 1 do
begin
// The section name is the key/ID.
ID := IDs[i];

// Append a row.
FData.Append;

// Read the values.
FData['ID'] := ID;
FData['Name'] := Source.ReadString(ID, 'Name', '');
// Names don't need to match. The field 'telephone' in this propriety
// format maps to 'phone' in your CSV output.
// Later, you can make this customizable (configurable) if you need to,
// but it's unlikely that you encounter two different inifile-based
// formats, so it's a waste to implement that until you need it.
FData['Phone'] := Source.ReadString(ID, 'Telephone', '');

FData.Post;
end;

finally
IDs.Free;
Source.Free;
end;
end;

关于delphi - 解析平面文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12460210/

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