【发布时间】:2015-05-29 13:41:56
【问题描述】:
我经常发现自己需要计算单词在多个文本字符串中出现的次数。当我这样做时,我想知道每个单词在每个文本字符串中分别出现了多少次。
我不相信我的方法非常有效,您能给我的任何帮助都会很棒。
通常,我会编写一个循环,(1) 从 txt 文件中提取文本作为文本字符串,(2) 执行另一个循环,循环使用正则表达式检查我想要计数的单词有多少每次将计数推送到数组时出现给定单词的次数,(3) 将用逗号分隔的计数数组打印到文件中。
这是一个例子:
#create array that holds the list of words I'm looking to count;
@word_list = qw(word1 word2 word3 word4);
#create array that holds the names of the txt files I want to count;
$data_loc = "/data/txt_files_for_counting/"
opendir(DIR1,"$data_loc")||die "CAN'T OPEN DIRECTORY";
my @file_names=readdir(DIR1);
#create place to save results;
$out_path_name = "/output/my_counts.csv";
open (OUT_FILE, ">>", $out_path_name);
#run the loops;
foreach $file(@file_names){
if ($file=~/^\./)
{next;}
#Pull in text from txt filea;
{
$P_file = $data_loc."/".$file;
open (B, "$P_file") or die "can't open the file: $P_file: $!";
$text_of_txt_file = do {local $/; <B>};
close B or die "CANNOT CLOSE $P_file: $!";
}
#preserve the filename so counts are interpretable;
print OUT_FILE $file;
foreach $wl_word(@word_list){
#use regular expression to search for term without any context;
@finds_p = ();
@finds_p = $text_of_txt_file =~ m/\b$wl_word\b/g;
$N_finds = @finds_p;
print OUT_FILE ",".$N_finds;
}
print OUT_FILE ",\n";
}
close(OUT_FILE);
我发现这种方法效率很低(缓慢),因为 txt 文件的数量和我要计算的单词数量不断增加。
有没有更有效的方法来做到这一点?
是否有一个 perl 包可以做到这一点?
在 python 中会更高效吗? (例如,是否有一个 python 包可以做到这一点?)
谢谢!
编辑:注意,我不想计算单词的数量,而是某些单词的存在。因此,这个问题“What's the fastest way to count the number of words in a string in Perl?”的答案并不完全适用。除非我错过了什么。
【问题讨论】:
-
您是否匹配大小写、完全匹配等...?还有 foo 和 foo! 呢,它们都被认为是 foo 的匹配项吗?
-
@PadraicCunningham,通常我已经清除了所有标点符号并将所有字符的大小写更改为小写。
-
那是python中的两行,要数一个字以上吗?
-
也是单行字还是怎么分隔的?