[英]Perl - Count occurrence of specific words for each line of file
做了很多搜索,沒有我想要的。 Perl菜鳥在這里。
我有一個已經整齊地組織成數據行的文本文件。 假設我感興趣的兩個字符串是“ hello”和“再見”。 我想編寫一個快速的Perl腳本,它將查看第一行並計算“ hello”和“再見”發生了多少次。 然后它將轉到下一行並進行計數,並添加到較早的計數中。 因此,在腳本末尾,我可以打印文件中每個字符串的計數總數。 逐行方法很重要的原因是因為我想使用多個計數,所以我可以打印兩個單詞在同一行中的次數,一行中僅包含一個單詞而不是單詞的次數。另外,一行包含一次“ hello”但多次包含“ byeby”等的次數。實際上,這是關於在一行中找到每個條件的次數,而不是單詞在整個文檔中出現的次數。
到目前為止,我在想:
#!/usr/bin/perl
use strict; use warnings;
die etc (saving time by not including it here)
my $word_a = "hello";
my $word_b = "goodbye";
my $single_both = 0; # Number of lines where both words appear only once.
my $unique_hello = 0; # Number of lines where only hello appears, goodbye doesn't.
my $unique_goodbye = 0; # Number of lines where goodbye appears, hello doesn't.
my $one_hello_multiple_goodbye = 0; # Number of lines where hello appears once and goodbye appears multiple times.
my $one_goodbye_multiple_hello = 0; # Number of lines where goodbye appears once and hello appears multiple times.
my $multiple_both = 0; = # Number of lines where goodbye and hello appear multiple times.
while (my $line = <>) {
Magic happens here
};
# then the results for each of those variables can be printed at the end.
正如我所說,我是菜鳥。 我對如何計算每一行中的出現次數感到困惑。 即使我知道我確定自己也會確定上面列出的所有不同條件。 我應該使用數組嗎? 散列? 還是考慮到我想要的東西,我完全朝錯誤的方向走了。 我需要計算在這些變量之后具有作為注釋列出的不同條件的行數。 任何幫助都將不勝感激!
您可以通過正則表達式計算某個單詞的出現次數,例如$hello = () = $line =~ /hello/g;
計算$line
hello
發生情況。 如何工作?
perl -n -E '$hello = () = /hello/g; $goodbye = () = /goodbye/g; say "line $.: hello - $hello, goodbye - $goodbye"; $hello_total += $hello; $goodbye_total += $goodbye;}{say "total: hello - $hello_total, goodbye - $goodbye_total";' input.txt
某些文件的輸出:
line 1: hello - 0, goodbye - 0
line 2: hello - 1, goodbye - 0
line 3: hello - 1, goodbye - 1
line 4: hello - 3, goodbye - 0
line 5: hello - 0, goodbye - 0
line 6: hello - 1, goodbye - 1
line 7: hello - 0, goodbye - 0
total: hello - 6, goodbye - 2
Perl有一個綁定運算符=~
,用於測試字符串是否與模式匹配。 您可以將其與兩個if語句結合使用,以從所有行中提取計數:
# only gathers counts
while (my $line = <STDIN>) {
$hello_cnt++ if $line =~ /hello/;
$goobye_cnt++ if $line =~ /goodbye/;
}
但是似乎您想逐行推理輸入,並且可以維護所有這些變量: $unique_hello
, $unique_goodbye
等...但是這對我來說似乎是很多額外的工作,您可以做什么對所有計數進行哈希處理:
my %seen;
while (my $line = <STDIN>) {
chomp $line; # remove trailing \n
map {
$seen{lc $_}++;
} split /\s+/, $line; # split on whitespace
}
現在,您具有以下結構的哈希值:
{
word1 => cnt1,
word2 => cnt2,
etc ...
}
現在,您可以打印總計:
print "Hello seen " . $seen{hello} . " times";
# etc ...
我為您做了逐行分析,希望這是一個很好的起點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.