Compiler construction Lex:一个计算输入中单词数的小程序
我对Lex非常陌生,这个问题的完整要求如下: 编写一个Lex输入文件,生成一个计数的程序 文本文件中的字符、单词和行,并报告计数。 将单词定义为字母和/或数字的任意序列,不带 标点符号或空格。标点符号和空格不算作 语言 现在我已经写下了代码:Compiler construction Lex:一个计算输入中单词数的小程序,compiler-construction,compilation,yacc,lex,Compiler Construction,Compilation,Yacc,Lex,我对Lex非常陌生,这个问题的完整要求如下: 编写一个Lex输入文件,生成一个计数的程序 文本文件中的字符、单词和行,并报告计数。 将单词定义为字母和/或数字的任意序列,不带 标点符号或空格。标点符号和空格不算作 语言 现在我已经写下了代码: %{ #include <stdio.h> #include <stdlib.h> int cno = 0, wno = 0, lno = 0; /*counts of characters, words and lines */
%{
#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;
}
我得到了输出
#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
我猜“字数”的错误应该是由于每一个字符的计数造成的,那么我应该如何修改我的程序来处理这个问题呢
此外,还有一些不必要的输出(那些标点符号)。我应该如何修改我的程序以避免它们
非常感谢。您需要一个规则来处理“无趣”字符;你还需要数一数 您不想拒绝换行符 在
word
的定义中不需要尾随上下文。您可能应该将大写字母作为字符
这似乎有效:
%{
#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;
}
标准的wc
命令(具有不同的“word”定义)产生:
这与行数和字符数一致。谢谢。您的代码中对需求有一些小的误解,但我已经解决了,并且我认为我已经找到了正确的代码。非常感谢。嗯……所以你不算非文字的字符?字符计数是单词中的字母字符,而不是标点符号和换行符等等?但是数字虽然是单词的一部分,却不算字符?有趣的定义;从这个问题上看不是很明显。但是有了这些定义和示例数据,您可以得到“正确答案”。您还可以使用lex内部变量yyleng而不是strlen()。
%{
#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
27 73 463 xyz.l