2014-11-06 3 views
2

줄 수, 단어 수, 문자 수를 인쇄하고 파일의 단어뿐만 아니라 발생하는 시간을 인쇄하려고합니다. 마지막 부분에 오류가 발생합니다 (즉, 단어를 출력하고 그 결과를 출력 함). 다른 모든 것은 잘 작동합니다.텍스트 파일에 단어 빈도 인쇄 Perl

오류 메시지는 내가 얻을 : 여기

Bareword found where operator expected at wc.pl line 34, near ""Number of lines: $lcnt\","Frequency" 
     (Missing operator before Frequency?) 
syntax error at wc.pl line 34, near ""Number of lines: $lcnt\","Frequency of " 
Can't find string terminator '"' anywhere before EOF at wc.pl line 34. 

내 코드입니다 :

샘플 입력을 txt 파일에서 :

#!/usr/bin/perl -w 

use warnings; 
use strict; 


my $lcnt = 0; 
my $wcnt = 0; 
my $ccnt = 0; 
my %count; 
my $word; 
my $count; 

open my $INFILE, '<', $ARGV[0] or die $!; 

while(my $line = <$INFILE>) { 

$lcnt++; 

$ccnt += length($line); 

my @words = split(/\s+/, $line); 

$wcnt += scalar(@words); 

     foreach $count(@words) { 
      $count{@words}++; 
     } 
} 

foreach $word (sort keys %count) { 


print "Number of characters: $ccnt\n","Number of words: $wcnt\n","Number of lines: $lcnt\","Frequency of words in the file: $word : $count{$word}"; 

} 

close $INFILE; 

이 내가 할 필요 무엇

This is a test, another test 
#test# 234test test234 

샘플 출력 :

Number of characters: 52 
Number of words: 9 
Number of lines: 2 
Frequency of words in the file: 
-------------------------------- 
#test#: 1 
234test: 1 
This: 1 
a: 1 
another: 1 
is: 1 
test: 1 
test,: 1 
test234: 1 

어떤 도움을 크게 감상 할 수있다!

답변

2

일부 논리 오류 및 코드에서 일부 변수 오용이 있습니다. 논리 오류의 경우 "문자 수"를 한 번만 인쇄해야하지만 인쇄해야하는 몇 개의 다른 문자와 함께 루프에 넣어야합니다 한 번만. 루프 밖으로 당겨 빼내십시오.

다음으로 정확하게 계산하지 않았습니다. foreach $count (@words) 행에 실제로 해당 단어를 사용하지 않았습니다. 그것이 제가 오용이라고 불렀던 것입니다. "$count{@words}++"은 분명히 원하는 것이 아닙니다.

오타가 한 개 있기 때문에 Perl이 구문 오류를 발생 시켰습니다. 그게 누락되었습니다 n에서 \n입니다. 쉬운 수정.

마지막으로 가능한 가장 좁은 범위에서 변수를 선언하는 것이 좋습니다. 여기가 볼 수있는 방법은 다음과 같습니다

my $lcnt = 0; 
my $wcnt = 0; 
my $ccnt = 0; 
my %count; 

while(my $line = <DATA>) { 

    $lcnt++; 
    $ccnt += length($line); 

    my @words = split(/\s+/, $line); 
    $wcnt += scalar(@words); 

    foreach my $word (@words) { 
     $count{$word}++; 
    } 
} 

print "Number of characters: $ccnt\n", 
     "Number of words: $wcnt\n", 
     "Number of lines: $lcnt\n", 
     "Frequency of words in the file:\n", 
     "-----------------------------------\n"; 

foreach my $word (sort keys %count) { 
    print "$word: $count{$word}\n"; 
} 

__DATA__ 
This is a test, another test 
#test# 234test test234 

난 그냥 편의상 지금은 __DATA__ 파일 핸들을 사용하여 전환. 입력 파일을 열어 다시 쉽게 전환 할 수 있습니다.

+1

도움에 감사드립니다! @DavidO – chomp

1

당신이 \ n을 의미 대신 문자열 인용의 끝을 탈출 \ "는 한 것 같습니다

변경에서;.

... "Number of lines: $lcnt\","Frequency of ... 

으로,

... "Number of lines: $lcnt\n","Frequency of ... 
관련 문제