Perl复杂数据结构-动态语言程序设计7

使用复杂数据结构处理问题

字典数据练习5

#处理字典
open(in,"dict1.txt");
while($Line=<in>)
{
chomp $Line; my %tr=(); #注意这里要使用局部变量以便单独分配内存
($word,$trans)=$Line=~/^(\S+)\=\>(.+)$/g;
@items=$trans=~/([^\;]+)/g;
foreach (@items)
{
$tr{$_}=0;
}
$dict{$word}=\%tr; #值为哈希的哈希
}
close(in);


open(in,"dict2.txt");
while($Line=<in>)
{
chomp $Line;
($word,$trans)=$Line=~/^(\S+)\=\>(.+)$/g;
@items=$trans=~/([^\;]+)/g;
foreach (@items)
{
${$dict{$word}}{$_}=0; #没有的项,perl可以自动创建
}
}
close(in);

#分层遍历输出
foreach $ele (sort keys %dict)
{
print $ele.'=>';
foreach $e (sort keys %{$dict{$ele}})
{
print $e.';';
}
print "\n";
}

Perl——字音对应表的生成。使用了复杂数据结构。语料为transcript.txt

#读取数据
open(in,"transcript.txt");
while($Line=<in>)
{
chomp $Line;
@array=$Line=~/([^\s\>]+)\[([^\]]+)\]/g;
for( $i=0;$i<@array-1;$i++ )
{
if($i%2==0)
{

@tmpChar=$array[$i]=~/(.{2})/g;
@tmpPy=$array[$i+1]=~/(\S+)/g;
for( $j=0;$j<@tmpChar;$j++ )
{
#值为哈希表的哈希表
${$dict{$tmpChar[$j]}}{$tmpPy[$j]}=0;
}
}

}
}
close(in);

#分层遍历输出
foreach $ele (sort keys %dict)
{
print $ele.":\t";
foreach $e (sort keys %{$dict{$ele}})
{
print $e.'; ';
}
print "\n";
}

Perl——历时字频处理任务的答案代码。使用了复杂数据结构。

#用来统计各个词在不同年份中的出现频率,形成词汇的生命曲线
$path="D:\\Documents\\desktop\\lex";
$year=1950;
opendir(DIR,$path);
@files=readdir(DIR);
closedir(DIR);

open(out,">mergedLEXS");
foreach $file (@files)
{
if($file=~/txt$/ )
{
print "is processing $file\n";
$file=~/^(\d+)/;
$year=$1;
$file=$path."\\".$file;
merge($file,$year);
}
}

close(out);

foreach $ele (sort keys %hash)
{
print out $ele."\t";
foreach $e (sort keys %{$hash{$ele}})
{
print out "year".$e.":".${$hash{$ele}}{$e}."\t";
}
print out "\n";
}



sub merge
{
my ($inp,$jahr)=@_;
open(in,"$inp");
while(<in>)
{
chomp;
$_=~/^(\S+)\s+(\S+)/;
${$hash{$1}}{$jahr}=$2;
}
close(in);
}



Related Articles

0 评论 :

发表评论

Quote Of The Day