在 Perl 中解析带双引号的制表符分隔文件
我有一个数据集,它是用双引号引起来的用户代理字符串制表符分隔的。我需要解析每一列并根据我的答案 其他帖子 我使用了 Text::CSV 模块。
94410634 0 GET "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB6.6; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; AskTB5.5)" 1
代码很简单。
#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV;
my $csv = Text::CSV->new(sep_char => "\t");
while (<>) {
if ($csv->parse($_)) {
my @columns = $csv->fields();
print "@columns\n";
} else {
my $err = $csv->error_input;
print "Failed to parse line: $err";
}
}
但是当我在此数据集上尝试时,出现 Failed to parse line:
错误。我做错了什么?我需要提取包含用户代理字符串的第四列以进行进一步处理。
I have a data set that is tab delimited with the user-agent strings in double quotes. I need to parse each of these columns and based on the answer of my other post I used the Text::CSV module.
94410634 0 GET "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB6.6; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; AskTB5.5)" 1
The code is a simple one.
#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV;
my $csv = Text::CSV->new(sep_char => "\t");
while (<>) {
if ($csv->parse($_)) {
my @columns = $csv->fields();
print "@columns\n";
} else {
my $err = $csv->error_input;
print "Failed to parse line: $err";
}
}
But i get the Failed to parse line:
error when I try it on this dataset. what am I doing wrong? I need to extract the 4th column containing the user-agent strings for further processing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的构造函数参数应该位于 hashref 中,而不是散列中:
my $csv = Text::CSV->new( { sep_char => "\t" } );
您确定数据集正是您所认为的那样吗?可能是某处缺少双引号或者没有制表符?
要验证文件内容,您使用的是 Unix/Linux 还是 Windows?在 unix 上,请运行以下命令:
cat -vet my_log_file_name | head -3
并检查输出是否在您期望制表符的位置包含空格或“^I”序列。cat -vet
将所有特殊字符打印为特殊可打印序列(TAB
=>^I
, newline =>$
等...)以下测试在我的 ActivePerl 上完美运行:
输出:
Your constructor arguments should be in a hashref, not a hash:
my $csv = Text::CSV->new( { sep_char => "\t" } );
Are you sure the dataset is exactly what you think it is? May be there's a double quote missing somewhere or there were no tabs?
To verify the file contents, are you on Unix/Linux or Windows? On unix, please run this:
cat -vet my_log_file_name | head -3
and check whether the output has spaces or "^I" sequences where you expect tabs.cat -vet
prints out all the special characters as special printable sequences (TAB
=>^I
, newline =>$
, etc...)The following test works perfectly on my ActivePerl:
Output: