TF,DF统计(perl),顶者有分

ectt0923 2006-03-16 10:48:45
小弟刚开始学PERL,用了一晚上实现以下功能:
输入一个目录名称,统计此目录下所有文件出现的单词及个数,并统计单词所属文件的个数:
#输入并获得目录
print "please input the directory: \n";
$dir=<STDIN>;
chomp($dir);
opendir(DIR,$dir)||die "cannot open the directory $dir";
chdir($dir)||die "cannot cd to $dir";

#读取目录下的文件名,并存入数组@file_array
$numf=0;
@file_array=();
foreach $name (sort readdir(DIR)){
$numf++;
push(@file_array,$name);
}
$old=shift(@file_array);
$old=shift(@file_array);
$numf=$numf-2;
#print @file_array;
#print $numf;

#读每一个文件,文件内容存入并取词存入@word[$j];
@os=();
@word=();
@wordsum=();
for($j=0;$j<$numf;$j++){
open(FILE,@file_array[$j])||die "cannot open the file: @file_array[$j] \n";
@file=<FILE>;
$fl=@file;
chomp(@file[0]);
$os[$j]=@file[0];
for($i=1;$i<$fl;$i++){
chomp(@file[$i]);
$os[$j]=$os[$j].@file[$i];
}
# print $os[$j];
print "\n after update: \n";
@temp=split(/\W+/,$os[$j]);
@wordsum=(@wordsum,@temp);
$nf=@temp;
@word[$j]=@temp[0];
for($k=1;$k<$nf;$k++){
@word[$j]=@word[$j]." ".@temp[$k];
}
# print @word[$j];
}
#print "\n the total words are: \n";
#print "@wordsum \n";

#利用HASH,先把TF设为0
foreach $w (@wordsum){
$words{$w}=0;
}
@difwords=keys(%words); #只取不相同的单词。
@difwords=sort @difwords;
#print %words;

#统计词的词数:
foreach $u (@wordsum){
$words{$u}++;
}
#print "\n the number of each word: \n";
print %words;

##new thing.to get the DF;
foreach $f (@difwords){
$df{$f}=0;
}
foreach $p (@difwords){
for($l=0;$l<$numf;$l++){
if(@word[$l]=~/\b$p\b/){
$df{$p}++;
}
}
}
print "\n the df is : \n";
print %df;

#格式化输出:
format TDF=
@<<<<<<<<<<<<<<<<<<<<<@<<<<<<<<<<@<<<<<<<<
$names,$words{$names},$df{$names}
============================================
.

open(TDF,">tdf.txt")||die "canot creat tdf";
foreach $names (@difwords){
write TDF;
}

想请教几个问题:
1.如何操纵多维数组,如a=((1,2,3),(2,3,4),(3,3,4)),如何表示a的第二个元素,即(2,3,4)
2,大家觉得perl的精华在什么地方,有人告诉我是正则表达式,HASH和引用,我却不认为引用有什么特别,比C中的引用功能强大吗?
3,欢迎高手简化以上程序.
...全文
124 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ectt0923 2006-03-26
  • 打赏
  • 举报
回复
没有人再提意见了吗?
xyzxyz1111 2006-03-17
  • 打赏
  • 举报
回复
用引用,把圆括号改成方括号
$a = [[1,2,3], [2,3,4], [3,3,4]];
@row2 = @$a[1];
michael_g_hu 2006-03-17
  • 打赏
  • 举报
回复
我顶就是了

37,719

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧