You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Perl实现文本文件两列组合并基于第三列统计计数

没问题,我来帮你搞定这个Perl脚本!你的需求核心是按Account和Template的组合分组,分别统计Active=Y和Active=N的次数对吧?之前用哈希没成功可能是键的组合方式没选对,或者计数逻辑有疏漏,下面直接上可运行的代码,再一步步解释细节:


完整Perl脚本

#!/usr/bin/perl
use strict;
use warnings;

# 定义输入输出文件路径
my $in_file = 'in.txt';
my $out_file = 'out.txt';

# 哈希存储统计结果:键为"Account|Template",值为数组[Active(Y)计数, NotActive(N)计数]
my %stats;

# 打开输入文件并处理
open my $in_fh, '<', $in_file or die "无法打开输入文件 $in_file: $!";
my $header = <$in_fh>; # 跳过第一行表头

while (my $line = <$in_fh>) {
    chomp $line;
    # 分割字段,兼容逗号后带空格的情况
    my ($template, $account, $active) = split /,\s*/, $line;
    # 用"Account|Template"作为唯一键,避免不同组合的键冲突
    my $key = "$account|$template";
    
    # 更新对应计数
    if ($active eq 'Y') {
        $stats{$key}[0]++;
    } elsif ($active eq 'N') {
        $stats{$key}[1]++;
    }
    # 确保未出现过的计数初始化为0,避免输出空值
    $stats{$key}[0] //= 0;
    $stats{$key}[1] //= 0;
}
close $in_fh;

# 写入输出文件
open my $out_fh, '>', $out_file or die "无法打开输出文件 $out_file: $!";
print $out_fh "Account,Template,Active,NotActive\n";

# 按Account升序、Template升序排序后输出(和示例顺序一致)
foreach my $key (sort {
    my ($a_acc, $a_temp) = split /\|/, $a;
    my ($b_acc, $b_temp) = split /\|/, $b;
    $a_acc <=> $b_acc || $a_temp <=> $b_temp
} keys %stats) {
    my ($account, $template) = split /\|/, $key;
    my ($active_cnt, $not_active_cnt) = @{$stats{$key}};
    print $out_fh "$account,$template,$active_cnt,$not_active_cnt\n";
}
close $out_fh;

print "统计完成,结果已写入 $out_file\n";

关键细节说明

  1. 哈希键的设计:用Account|Template作为唯一标识,避免比如Account=123+Template=456和Account=12+Template=3456这类组合被误判为同一个键。
  2. 计数初始化:用//= 0确保即使某类状态(比如Y或N)没有记录,也能输出0而不是空值,符合你的示例要求。
  3. 排序处理:默认哈希是无序的,通过sort块按Account和Template升序排列,让输出顺序和你给出的示例完全一致。

测试验证

把你的示例输入整理成标准的in.txt:

Template,Account,Active
123456,123,N
123456,456,Y
321478,456,Y
123456,123,N
321478,456,Y

运行脚本后,out.txt会生成:

Account,Template,Active,NotActive
123,123456,0,2
456,123456,1,0
456,321478,2,0

完全匹配你的预期输出。

内容的提问来源于stack exchange,提问作者user9259206

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:58:08