分类器C语言,基于朴素贝叶斯分类器的文本分类算法(C语言)

基于朴素贝叶斯分类器的文本分类算法(C语言)

#include

#include //_getcwd(), _chdir()

#include //_MAX_PATH, system()

#include //_finddata_t, _findfirst(), _findnext(), _findclose()

char vocabulary[1000][20];/*声明公有二维数组,用来存储分割好的单词*/

/*=================将要分类的文本分割成单词存储在二维数组vocabulary中================*/

//@输入参数:要分类的文本

//@输出参数:该文本中总单词数

int SplitToWord(char text[])

{

int i=0;

char seps[]=", .\n"; /*定义单词的分隔符*/

char *substring;

/******利用分隔符将文本内容分割成单词并存储******/

substring=strtok(text,seps);

while(substring!=NULL)

{

strcpy(vocabulary[i],substring);//将单词存储到vocabulary数组中

substring=strtok(NULL,seps);

i++;

}

return i; //返回一共多少个单词

}

/*===============================计算该目录下的文件数================================*/

//@输入参数:无

//@输出参数:该目录下.txt文件数

int CountDirectory()

{

int count=0; //txt文件计数器

long hFile;

_finddata_t fileinfo;

/********查找.txt文件,记录文件数**********/

if ((hFile=_findfirst("*.txt",&fileinfo))!=-1L)

{

do

{

count++;

} while (_findnext(hFile,&fileinfo) == 0);

}

return count;

}

/*===================================计算某类别中∏P(ai|vj)===================================*/

//@输入参数:分类文本中单词数

//@输出参数:该类别下∏P(ai|vj)

float CalculateWordProbability(int wordCount)

{

int countSame; //分类文本中的某单词在所有训练样本中出现次数

int countAll=0; //训练样本中总单词数

char token;

FILE *fp;

float wordProbability=1; //为后面联乘做准备

int i,j;

long hFile;

_finddata_t fileinfo;

for(j=0;j

{

countSame=0;

countAll=0;

if((hFile=_findfirst("*.txt",&fileinfo))!=-1L) //对于该类别下每一个.txt文本

{

do

{

if((fp=fopen(http://doc.docsou.com,"r"))==NULL) //是否能打开该文本

{

printf("Sorry!Cannot open the file!\n");

exit(0);

}

/********存储此.txt文件中每个单词并与分类文本的单词作比较*******/

while((token = fgetc(fp)) != EOF)

{

char keyword[1024];

i = 0;

keyword[0] = token; // 将每个词第一个字符赋给数组第一个元素

while ((keyword[++i] = fgetc(fp)) != ' ' && keyword[i] != '\t' && keyword[i] != EOF && keyword[i] != '\n'); // 开始读字符,直到遇到空白符,说明找到一个词

keyword[i] = '\0';// 加结束符

countAll++;

if (strcmp(keyword,vocabulary[j]) == 0) //比较两个单词是否相同

countSame++;

}

fclose(fp);

}while (_findnext(hFile,&fileinfo) == 0);

}

wordProbability*=

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值