lex demo

%{
enum {
	LOOKUP =0,
	VERB,
	ADJ,
	CONJ
};

int state;
int add_word(int type, char *word);
int lookup_word(char *word);
%}

%option noyywrap
%%
\n		{state = LOOKUP;}
^VERB		{state = VERB;}
^ADJ		{state = ADJ;}
^CONJ		{state = CONJ;}

.	;/*ignore anything else*/
[a-zA-Z]+ {
		/*a normal word , define it or look it up */
        if(state != LOOKUP)
	{
		/* define the current word */
		add_word(state, yytext);
	}else{
	switch(lookup_word(yytext)){
	case VERB: printf("%s is verb\n",yytext); break;
	case ADJ:  printf("%s is adj\n",yytext); break;
	case CONJ: printf("%s is conj\n",yytext); break;
	default:    printf("oh, i can't recognize it!!\n");break;	
	 }
	}	

}








%%
main()
{
   yylex();
}
/*define a linked list of words and types*/


struct word *word_list; /*first element in word list */
extern void *malloc();
struct word{
	char *word_name;
	int word_type;
	struct word *next;
};
int 
add_word(int type, char *word)
{
	if(lookup_word(word) != 0)
		return 0;

/*word not there, allocate a new entry and link it on the list*/
	struct word *tem;

	tem = malloc(sizeof(struct word));
	
	tem->next = word_list;



	char *c = malloc(sizeof(char)*(strlen(word)+1));
	strcpy(c,word);
	tem->word_name = c;
	tem->word_type = type;

	word_list = tem;
	return 1;
	
}
int 
lookup_word(char *word)
{
	struct word *t = word_list;
	for(;t;t = t->next)
	{
	    int r = strcmp(word, t->word_name);
	    if(r ==0)	return t->word_type;
		
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值