2012-05-09 2 views
2

内の単語をカウントする小さなプログラム私はレックスに非常に新しいですし、次のようにこの問題の完全な要件は次のとおりです。レックス:入力

は数えるプログラムを生成しますLexの入力ファイルを書きます 文字ファイル内の文字、単語、行を検索し、カウントを報告します。 の句読点またはスペースを使用せずに、任意の文字および/または数字のシーケンスを単語として定義します。句読点と空白は、 という単語には数えられません。今、私はコードを書き留めてきた

%{ 
#include <stdio.h> 
#include <stdlib.h> 
int cno = 0, wno = 0, lno = 0; /*counts of characters, words and lines */ 
%} 
character [a-z] 
digit [0-9] 
word ({character}|{digit})+[^({character}|{digit})] 
line \n 
%% 
{line} { lno++; REJECT; } 
{word} { wno++; REJECT; } 
{character} { cno++; } 
%% 
void main() 
{ yylex(); 
    fprintf(stderr, "Number of characters: %d; Number of words: %d; Number of lines: %d\n", cno, wno, lno); 
    return; 
} 

を私は、テキストファイルでそれをテストした:

this is line #1 
line #2 is here 
[email protected]#$%^&*() 
haha hey hey 

そして私は、出力

#1 
#2 
[email protected]#$%^&*() 

Number of characters: 30; Number of words: 45; Number of lines: 4 

を得たが、正しい出力は

です。
Number of characters: 30; Number of words: 11; Number of lines: 4 

私は「文字数」のエラーは文字数が多いため何とかなるはずだと思うので、これに取り組むために私のプログラムをどのように修正すればよいですか?

また、不要な出力が出てきます(これらの句読点)。プログラムを修正するにはどうしたらよいですか?

ありがとうございました。

答えて

9

「興味のない」文字を処理するルールが必要です。あなたはまだそれらを数える必要があります。

改行を拒否したくありません。

wordの定義に後続のコンテキストは必要ありません。おそらく大文字はcharacterとしてください。

これは動作するようです:

%{ 
#include <stdio.h> 
#include <stdlib.h> 
int cno = 0, wno = 0, lno = 0; /*counts of characters, words and lines */ 
%} 

character [a-zA-Z] 
digit [0-9] 
word ({character}|{digit})+ 
line \n 

%% 

{line} { cno++; lno++; } 
{word} { wno++; cno += strlen(yytext); } 
. { cno++; } 

%% 

int main(void) 
{ 
    yylex(); 
    printf("Number of characters: %d; ", cno); 
    printf("Number of words:  %d; ", wno); 
    printf("Number of lines:  %d\n", lno); 
    return 0; 
} 

独自のソースコードを実行すると、出力がされた:

Number of characters: 463; Number of words:  65; Number of lines:  27 

(「単語」の異なる定義を持っている)標準wcコマンド

27  73  463 xyz.l 

これは、行と文字の数に一致します。

+0

ありがとうございます。あなたのコードには、いくつかの小さな誤解がありますが、私はそれらを理解しました。私は正しいコードを思いついたと思います。どうもありがとう。 – goldfrapp04

+0

ええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええええ文字数は単語のアルファベット文字であり、句読点や改行などではありません。しかし、数字は単語の一部ですが、文字としてカウントされませんか?興味深い定義;その質問からすぐには分かりません。しかし、これらの定義とサンプルデータを使用すると、「正解」で終わることができます。 –

+1

strlen()を使用する代わりに、lex内部変数yylengを使用することもできます。 – neo1691