gpt4 book ai didi

perl - 从哈希 perl 写入 CSV 文件

转载 作者:行者123 更新时间:2023-12-02 07:51:16 25 4
gpt4 key购买 nike

我有一个程序,目前从 FILE 1 读取,如下所示并匹配某些字符。例如

Type, Fruit, Description, quantitytropical, banana, tasty and yummy, 5tropical, grapefruit, bitter and not yummy, 2... and so on

First of all I wanted to create hash of hashes for each 'Type', 'Fruit', 'Description', 'Quantity' and store the different values in the reference hashes. That works fine with the code below.

use strict;
use warnings;
use Data::Dumper;
use Text::CSV;

my %MacroA = ('Type' => {}, 'Fruit' => {}, 'Description' => {}, 'Quantity' => {});

open (my $file, '<', 'FRUITIES.txt') or die $!;

while (my $line = <$file>) {

if ($line =~ /\b(tropical)\b,/) {
$MacroA{Type}->{$1}++;
}

if ($line =~ /,\b(banana|grapefruit)\b,/) {
$MacroA{Fruit}->{$1}++;
}

if ($line =~ /,([\w\s]+?),/) {
$MacroA{Description}->{$1}++;
}

if ($line =~ /,([\d]+?)/) {
$MacroA{Quantity}->{$1}++;
}
}

close $file;

所以我的问题是如何将这些数据(数据不固定)放入 csv 文件或任何相关文件(可能是 xls)中,这将是一个表,其中包含每个哈希值的列(“类型” 、“水果”、“描述”、“数量”)。

最佳答案

我同意哈希值的哈希值是一件好事,但我认为您没有以可以轻松检索的方式存储它。

您可以这样做的一种方法是这样的。

{ id_1 => {
data_1 => "blah",
data_2 => "foo",
...
},
id_2 => {
...
},
...
}

首先,您需要选择哪一列作为“ID”。这将决定每个 ROW 的唯一性。假设您的示例中让我们选择水果,因为我们假设不会有两个水果出现在同一个文件中。所以我们会有这样的东西:

{ banana => {
type => "tropical",
description => "tasty and yummy",
...
},
grapefruit => {
...
},
...
}

为了将其更改回 CSV,我们循环遍历哈希值。

my %fruit_data; #let's assume that this already has the data in it

foreach my $fruit ( keys %fruit_data ) {

#given the $fruit you can now access all the data you need
my $type = %fruit_data{$fruit}{'type'};
my $desc = %fruit_data{$fruit}{'description'};
# etc...

# then you may want to store them in a scalar in any order you want
my $row = "$field,$type,$desc etc.\n";

# then work your way from there

}

关于perl - 从哈希 perl 写入 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13588129/

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