gpt4 book ai didi

perl - 是否有用于解析柱状文本的 Perl 模块?

转载 作者:行者123 更新时间:2023-12-04 07:08:14 27 4
gpt4 key购买 nike

假设我有一个制表符分隔的文本文件,其中包含按列排列的数据(带有标题)。

不同的列可能会“堆叠”成类似“工作表”的排列,即有一些分隔线(可能提前知道也可能不知道)允许垂直排列不同的列。

是否有一个 Perl 模块可以帮助将此文本文件中的列数据解析为数据结构(例如,一个哈希表,其中键是列标题,值是列数据标量数组)?

编辑 通过“堆叠”,我的意思是一列文本可能包含多个单独的数据“向量”,每个“向量”都有不同的标题和不同的长度。诚然,这使解析变得复杂。

编辑 老实说,我不确定困惑在哪里。尽管如此,这里有一个例子:

header_one\theader_three
data_1\tdata_7
data_2\tdata_8
data_3\tdata_9
\tdata_10
header_two\tdata_11
data_4\theader_four
data_5\tdata_12
data_6\tdata_13
\tdata_14

该脚本会将其转换为具有四个键的哈希表: header_one , header_two , header_three , 和 header_four ,每个键引用指向 data_n 的数组引用标题下方的元素。

最佳答案

我认为这与您所说的很接近。如果列数发生变化,则将输入视为不同的表。可以轻松修改此代码以识别其他标记(例如等号行),而不是使用列计数。

#!/usr/bin/perl

use strict;
use warnings;

use Text::CSV_XS;

#setup the parser, here we want tab separated and we allow
#loose quoting, so qq/foo\t"bar\tbaz"\tquux/ is
#("foo", "bar\tbaz", "quux")
my $p = Text::CSV_XS->new(
{
sep_char => "\t",
allow_loose_quotes => 1,
}
);

my @stacked;
my $cur = 0;
while (<>) {
$p->parse($_) or die $p->error_input;
my @rec = $p->fields;
#normal case, just add the record to the last
#section in @stacked
if (@rec == $cur) {
push @{$stacked[-1]}, \@rec;
next;
}
#if the number of columns don't match then
#we have a new section
push @stacked, [\@rec];
$cur = @rec; #set the new number of columns
}

for my $table (@stacked) {
print "header: ", join("::", @{$table->[0]}), "\n";
for my $i (1 .. $#$table) {
print "data: ", join("::", @{$table->[$i]}), "\n";
}
print "\n";
}

关于perl - 是否有用于解析柱状文本的 Perl 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/774861/

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