Lex program to count the frequency of the given word in a file
Problem: Given a text file as input, the task is to count frequency of a given word in the file.
Explanation:
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
Approach:
As we know, yytext holds the value of current matched token, we can compare it with the word whose frequency is to be counted. if the value of yytext and the given word are same, increment the count variable.
Input File: input.txt
Below is the implementation of above approach:
C
%{
#include<stdio.h>
#include<string.h>
char word [] = "geeks" ;
int count = 0;
%}
%%
[a-zA-Z]+ { if ( strcmp (yytext, word)==0)
count++; }
. ;
%%
int yywrap()
{
return 1;
}
int main()
{
extern FILE *yyin, *yyout;
yyin= fopen ( "input.txt" , "r" );
yylex();
printf ( "%d" , count);
}
|
Output:
Last Updated :
10 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...