今天写了一个敏感词过滤的程序,可以对中英文敏感词 进行过滤,对与文中出现敏感词但是敏感词中间有的空格还有换行的可以进行处理
#includeiostream
#includestdlib.h
#includestring
#includebitset
#includemap
#includefstream
#define NUM 60
using namespace std;
int cmp(const void *a,const void *b)
{
int *x=(int *)a;
int *y=(int *)b;
return (*y)-(*x);
}
// 匹配的字符串 敏感词统计 敏感词大小数组
void find(string &p,mapstring,int &word, int *b ,int len )
{
int i=0,j;
string str;
mapstring,int::iterator l_it;
while(p[i]!=' ')
{
for(j=0;jlen&&b[j]!=0;)
{
str=p.substr(i,b[j]);
if(str.empty())
{
j++;
continue;
}
l_it=word.find(str);
if(l_it==word.end())
{ j++;
continue;
}
else
{
word[str]++;
for(int loop=i;loopi+b[j];loop++)
p[loop]=' ';//已经去掉了空格。再次加上表明是敏感词。
i+=b[j];// 匹配成功则i从匹配之后的位置开始进行继续匹配。
i--;
break;
}
}
i++;
}
}
int main()
{
mapstring ,int mapWord;
mapstring,int::iterator l_it;
int lenFile=-1,lenstr=0;
char w;;
string p="",arr=" ",str;
char ch[300]="";
int i,j,max,wordLen[20],len;//假设敏感词的长度最多有10种
memset(wordLen,0,sizeof(wordLen));
//提取敏感词
ifstream in("word.txt");
max=0;
len=0;
while(instr)
{
if(!str.empty())
{
l_it= mapWord.find(str);
if(l_it==mapWord.end())
{
mapWord[str]=-1;
len++;
}
max=str.length();
if(wordLen[max]==0)
{
wordLen[max]=max;
}
}
}
qsort(wordLen,len,sizeof(wordLen[0]),cmp);
in.close();
cout"(1) 获取原文:";
ifstream fin("test.txt");
memset(ch,'%',sizeof(ch));
while(fin.get(w))
{
coutw;
lenFile++;
if(w=='')
ch[lenFile]='#';
else if(w==' ')
ch[lenFile]='*';
else
{
arr[0]=w;
arr[1]=' ';
p+=arr;
}
}
fin.close();
cout" (2) 去除换行符,空格之后"endl;
coutpendl;
find(p,mapWord,wordLen,len);
cout"(3) 敏感词过滤之后:"endl;
for(i=0,j=0;j=lenFile;j++)
{
if(ch[j]=='%')
{
if(p[i]==' ')
cout"*";
else
coutp[i];
i++;
}
else if(ch[j]=='#')
coutendl;
else if(ch[j]=='*')
cout" ";
}
cout"_________________________________________________________";
cout"(4) 统计敏感词出现的个数";
for(l_it=mapWord.begin();l_it!=mapWord.end();l_it++)
if(l_it-second!=-1)
cout" "l_it-first"t "l_it-second+1;
cout"thanks!";
}













