count frequency of occurrence of a word - lex program
LEX code to count the frequency of the given word(sachin) in an input.txt file
***************************************************
%{
#include<stdio.h>
#include<string.h>
char word [] = "sachin";
int count = 0;
%}
%option noyywrap
/* Rule Section */
%%
[a-zA-Z]+ { if(strcmp(yytext, word)==0)
count++; }
. ;
\n ;
%%
/* code section */
int main()
{
extern FILE *yyin, *yyout;
/* open the input file
in read mode */
yyin=fopen("input.txt", "r");
yylex();
printf("No of occurance of the word %s=%d\n",word, count);
}
Execution
the input.txt file is
$ cat input.txt
this is a test file
to check frequncy of the word sachin
it will count how many times word sachin
occures in the file and count the word sachin
$ flex freq.lex
$ gcc lex.yy.c
$ ./a.out
No of occurance of the word sachin=3
Comments
Post a Comment