Не знаю ни о каком пакетном решении, но что-то не очень гибкое довольно просто сделать, предполагая, что вы можете сделать два прохода по файлу: (ниже приведен частично пример псевдокода Perlish)
- Предположение: данные могут содержать пробелы и НЕ заключаются в кавычки аля CSV, если есть пробел - если это не так, просто используйте
Text::CSV(_XS)
.
- Предположение: для форматирования не используются вкладки.
- Логика определяет «разделитель столбцов» как любой последовательный набор вертикальных строк, заполненных пробелами на 100 %.
- Если случайно в каждой строке есть пробел, который является частью данных со смещением M символов, логика будет считать смещение M разделителем столбцов, поскольку она не может знать ничего лучшего. ЕДИНСТВЕННЫЙ способ узнать лучше, если вы требуете, чтобы разделение столбцов было не менее X пробелов, где X>1 — см. второй фрагмент кода для этого.
Образец кода:
my $INFER_FROM_N_LINES = 10; # Infer columns from this # of lines
# 0 means from entire file
my $lines_scanned = 0;
my @non_spaces=[];
# First pass - find which character columns in the file have all spaces and which don't
my $fh = open(...) or die;
while (<$fh>) {
last if $INFER_FROM_N_LINES && $lines_scanned++ == $INFER_FROM_N_LINES;
chomp;
my $line = $_;
my @chars = split(//, $line);
for (my $i = 0; $i < @chars; $i++) { # Probably can be done prettier via map?
$non_spaces[$i] = 1 if $chars[$i] ne " ";
}
}
close $fh or die;
# Find columns, defined as consecutive "non-spaces" slices.
my @starts, @ends; # Index at which columns start and end
my $state = " "; # Not inside a column
for (my $i = 0; $i < @non_spaces; $i++) {
next if $state eq " " && !$non_spaces[$i];
next if $state eq "c" && $non_spaces[$i];
if ($state eq " ") { # && $non_spaces[$i] of course => start column
$state = "c";
push @starts, $i;
} else { # meaning $state eq "c" && !$non_spaces[$i] => end column
$state = " ";
push @ends, $i-1;
}
}
if ($state eq "c") { # Last char is NOT a space - produce the last column end
push @ends, $#non_spaces;
}
# Now split lines
my $fh = open(...) or die;
my @rows = ();
while (<$fh>) {
my @columns = ();
push @rows, \@columns;
chomp;
my $line = $_;
for (my $col_num = 0; $col_num < @starts; $col_num++) {
$columns[$col_num] = substr($_, $starts[$col_num], $ends[$col_num]-$starts[$col_num]+1);
}
}
close $fh or die;
Теперь, если вы требуете, чтобы расстояние между столбцами было не менее X пробелов, где X>1, это также выполнимо, но синтаксический анализатор расположения столбцов должен быть немного сложнее:
# Find columns, defined as consecutive "non-spaces" slices separated by at least 3 spaces.
my $min_col_separator_is_X_spaces = 3;
my @starts, @ends; # Index at which columns start and end
my $state = "S"; # inside a separator
NEXT_CHAR: for (my $i = 0; $i < @non_spaces; $i++) {
if ($state eq "S") { # done with last column, inside a separator
if ($non_spaces[$i]) { # start a new column
$state = "c";
push @starts, $i;
}
next;
}
if ($state eq "c") { # Processing a column
if (!$non_spaces[$i]) { # First space after non-space
# Could be beginning of separator? check next X chars!
for (my $j = $i+1; $j < @non_spaces
|| $j < $i+$min_col_separator_is_X_spaces; $j++) {
if ($non_spaces[$j]) {
$i = $j++; # No need to re-scan again
next NEXT_CHAR; # OUTER loop
}
# If we reach here, next X chars are spaces! Column ended!
push @ends, $i-1;
$state = "S";
$i = $i + $min_col_separator_is_X_spaces;
}
}
next;
}
}
person
DVK
schedule
14.10.2010