Lex:一个计算输入中单词的小程序

gol*_*p04 2 compiler-construction yacc lex compilation

我对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;
}
Run Code Online (Sandbox Code Playgroud)

我用文本文件测试了它:

this is line #1
line #2 is here
!@#$%^&*()
haha hey hey
Run Code Online (Sandbox Code Playgroud)

我得到了输出

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

Number of characters: 30; Number of words: 45; Number of lines: 4
Run Code Online (Sandbox Code Playgroud)

但正确的输出应该是

Number of characters: 30; Number of words: 11; Number of lines: 4
Run Code Online (Sandbox Code Playgroud)

我想"字数"的错误应该以某种方式归因于每个字符的数量,所以我应该如何修改我的程序来解决这个问题呢?

此外,还有一些不必要的输出(那些标点符号).我应该如何修改我的程序以避免它们?

非常感谢你.

Jon*_*ler 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;
}
Run Code Online (Sandbox Code Playgroud)

在自己的源代码上运行时,输出为:

Number of characters: 463; Number of words:      65; Number of lines:      27
Run Code Online (Sandbox Code Playgroud)

标准wc命令(具有不同的'word'定义)产生:

  27      73     463 xyz.l
Run Code Online (Sandbox Code Playgroud)

这同意行数和字符数.

  • 您也可以使用lex内部变量yyleng而不是使用strlen()。 (3认同)