2

私はLexを初めて使用します。この問題の完全な要件は、次のとおりです。

テキストファイル内の文字、単語、および行をカウントし、カウントを報告するプログラムを生成する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
!@#$%^&*()
haha hey hey

そして、私は出力を得ました

   #1
 #2  
!@#$%^&*()

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

しかし、正しい出力は

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

「単語数」のエラーは、文字数ごとにどういうわけか原因だと思いますが、これに対処するためにプログラムをどのように変更すればよいでしょうか。

また、不要な出力(句読点)が出てきます。それらを回避するためにプログラムをどのように変更する必要がありますか?

どうもありがとうございます。

4

1 に答える 1

10

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

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

の定義に末尾のコンテキストは必要ありません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コマンド(「word」の定義が異なります)は次のようになります。

  27      73     463 xyz.l

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

于 2012-05-09T04:58:57.390 に答える