Recent

Author Topic: Detecting the delimiter in a CSV file  (Read 597 times)

maurobio

  • Hero Member
  • *****
  • Posts: 623
  • Ecology is everything.
    • GitHub
Detecting the delimiter in a CSV file
« on: December 10, 2019, 12:56:13 pm »
Dear ALL,

Python csv module has a class with a handy method sniff() which allows to deduce the format of a CSV file, with an optional parameter containing possible valid delimiter characters.

It would be very useful to have a similar function in (Free) Pascal, which would return simply a char indicating the delimiter character:

Code: Pascal  [Select][+][-]
  1. function Sniff(sample: string; validchars: TSysCharSet = [',', ';', '|', #8]): char;

Such a function could be used as:

Code: Pascal  [Select][+][-]
  1. var
  2.    S: string;
  3.  
  4. begin
  5.    S := 'Col1; Col2; Col3';
  6.    WriteLn('Delimiter = "', Sniff(S), '"');
  7. end.
  8.  

which should return ";" in the above example.

Has someone implemented something like that? It should be simple enough, but I could not figure out how to implement it taking into account the possible existence of the delimiter character inside each data column, eg.:

Code: Pascal  [Select][+][-]
  1. S := '"Col 1, valid data", "Col2", "Col3"';

Any hints?

Best regards,
UCSD Pascal / Burroughs 6700 / Master Control Program
Delphi 7.0 Personal Edition
Lazarus 2.0.12 - FPC 3.2.0 on GNU/Linux Mint 19.1, Lubuntu 18.04, Windows XP SP3, Windows 7 Professional, Windows 10 Home

 

TinyPortal © 2005-2018