나는 펄 초보자 해요 내 숙제 중 하나에 나는이 같은 솔루션을 함께했다 : 나는 무엇을 언급 주석을 포함했다이 더 펄에서 수행 할 수있는 방법을 방법
#wordcount.pl FILE
#
#if no filename is given, print help and exit
if (length($ARGV[0]) < 1)
{
print "Usage is : words.pl word filename\n";
exit;
}
my $file = $ARGV[0]; #filename given in commandline
open(FILE, $file); #open the mentioned filename
while(<FILE>) #continue reading until the file ends
{
chomp;
tr/A-Z/a-z/; #convert all upper case words to lower case
tr/.,:;!?"(){}//d; #remove some common punctuation symbols
#We are creating a hash with the word as the key.
#Each time a word is encountered, its hash is incremented by 1.
#If the count for a word is 1, it is a new distinct word.
#We keep track of the number of words parsed so far.
#We also keep track of the no. of words of a particular length.
foreach $wd (split)
{
$count{$wd}++;
if ($count{$wd} == 1)
{
$dcount++;
}
$wcount++;
$lcount{length($wd)}++;
}
}
#To print the distinct words and their frequency,
#we iterate over the hash containing the words and their count.
print "\nThe words and their frequency in the text is:\n";
foreach $w (sort keys%count)
{
print "$w : $count{$w}\n";
}
#For the word length and frequency we use the word length hash
print "The word length and frequency in the given text is:\n";
foreach $w (sort keys%lcount)
{
print "$w : $lcount{$w}\n";
}
print "There are $wcount words in the file.\n";
print "There are $dcount distinct words in the file.\n";
$ttratio = ($dcount/$wcount)*100; #Calculating the type-token ratio.
print "The type-token ratio of the file is $ttratio.\n";
그 않습니다. 실제로 주어진 텍스트 파일에서 단어 수를 찾아야합니다. 위의 프로그램의 출력은 다음과 같습니다.
The words and their frequency in the text is:
1949 : 1
a : 1
adopt : 1
all : 2
among : 1
and : 8
assembly : 1
assuring : 1
belief : 1
citizens : 1
constituent : 1
constitute : 1
.
.
.
The word length and frequency in the given text is:
1 : 1
10 : 5
11 : 2
12 : 2
2 : 15
3 : 18
There are 85 words in the file.
There are 61 distinct words in the file.
The type-token ratio of the file is 71.7647058823529.
Google의 도움을 받아도 숙제에 대한 해결책을 찾을 수는 있지만. 하지만 Perl의 진정한 힘을 사용하는 작고 간결한 코드가있을 것이라고 생각합니다. 누구나 코드 줄이 훨씬 적은 펄 솔루션을 나에게 줄 수 있습니까?
, 파일 이름은 두 번째 인수입니다. 그건 당신의 코드와 모순된다. –
제안 사항은 다음과 같습니다. 명시 적으로 열기를 사용하지 마십시오. <> 만 사용하십시오. Perl은 ARGV의 각 인수를 파일 이름으로 해석하고 <>는 파일 이름을 읽습니다. –
@WilliamPursell : 예 파일 이름은 두 번째 인수입니다. – sriram