为了提高查找效率,这里将敏感词用树形结构存储,每个节点有一个map成员,其映射关系为一个string对应一个TreeNode。

STL::map是按照operator<比较判断元素是否相同,以及比较元素的大小,然后选择合适的位置插入到树中。为了提高map的插入及查询效率,可以选用hash_map或unordered_map。关于他们的效率,可以参考http://blog.csdn.net/whizchen/article/details/9286557

下面主要实现了TreeNode类,进行节点的插入以及查询。(这里命名用Trie比较专业)

 #include<map>
#include<string>
//#include<unordered_map>
using namespace std; class Tree;
class TreeNode
{
friend class Tree;
typedef map<string,TreeNode> _TreeMap;
typedef map<string,TreeNode>::iterator _TreeMapIterator;
// typedef unordered_map<string,TreeNode> _TreeMap;
// typedef unordered_map<string,TreeNode>::iterator _TreeMapIterator;
private:
string m_character;
_TreeMap m_map;
TreeNode* m_parent;
public:
TreeNode(string character);
TreeNode(){
m_character="";
};
string getCharacter() const;
TreeNode* findChild(string& nextCharacter);
TreeNode* insertChild(string& nextCharacter); };

TreeNode.h

#include <iostream>
#include "TreeNode.h"
using namespace std; string TreeNode::getCharacter() const
{
return m_character;
} TreeNode::TreeNode(string character)
{
if (character.size() == )
m_character.assign(character);
else
cout<<"error";
} TreeNode* TreeNode::findChild(string& nextCharacter)
{
_TreeMapIterator TreeMapIt = m_map.find(nextCharacter); //利用map/unordered_map进行查找
return (TreeMapIt == m_map.end()) ? NULL :&TreeMapIt->second;
return NULL;
} TreeNode* TreeNode::insertChild(string& nextCharacter)
{
if(!findChild(nextCharacter)) //添加节点,并返回节点位置
{
m_map.insert(pair<string, TreeNode>(nextCharacter, TreeNode(nextCharacter)));
return &(m_map.find(nextCharacter)->second);
}
return NULL;
}

TreeNode.cpp

接下来实现这个tree,在建立TreeNode树时,以parent为根节点建立,一开始parent为m_emptyRoot,然后把keyword按照规则添加到树中,假设一开始m_emptyRoot为空,keyword为"敏感词",则会以"敏感词"为一条分支建立成为一颗树枝'敏'->'感'->'词',此后,若想再添加"敏感度",由于"敏感词"与"敏感度"的前两个字相同,则会在'敏'->'感'->'词'的基础上,从字'感'开始新生长出一颗分支,即'敏'->'感'->'度',这两颗分支共用'敏'->'感'。

程序中暂时考虑中文的情况,如果需要考虑英文或中英文结合的情况,将PACE改为1,另外程序做出部分修改即可。

下面代码实现了Tree类,进行树的构成及查询。

 #include "TreeNode.h"
using namespace std; class Tree
{
public:
int count; //当前查找的一个敏感词的字数
TreeNode* insert(string& keyword);
TreeNode* insert(const char* keyword);
TreeNode* find(string& keyword);
Tree(){
count = ;
};
private:
TreeNode m_emptyRoot;
int m_pace;
TreeNode* insert(TreeNode* parent, string& keyword);
TreeNode* insertBranch(TreeNode* parent, string& keyword);
TreeNode* find(TreeNode* parent,string& keyword); };

Tree.h

 #include "Tree.h"
#include<iostream> #define PACE 2 //如果需要考虑英文或中英文结合的情况,将PACE改为1,另外程序还需要做部分修改 TreeNode* Tree::insert(string& keyword)
{
return insert(&m_emptyRoot, keyword);
} TreeNode* Tree::insert(const char* keyword)
{
string wordstr(keyword);
return insert(wordstr);
} TreeNode* Tree::insert(TreeNode* parent, string& keyword)
{
if(keyword.size()==)
return NULL;
string firstChar=keyword.substr(,PACE);
TreeNode* firstNode = parent->findChild(firstChar);
if(firstNode==NULL)
return insertBranch(parent,keyword);
string restChar=keyword.substr(PACE,keyword.size());
return insert(firstNode,restChar);
} TreeNode* Tree::insertBranch(TreeNode* parent,string& keyword)
{
string firstChar=keyword.substr(,PACE);
TreeNode* firstNode = parent->insertChild(firstChar);
if(firstNode!=NULL)
{
string restChar=keyword.substr(PACE,keyword.size());
if(!restChar.empty())
return insertBranch(firstNode,restChar);
}
return NULL;
} TreeNode* Tree::find(string& keyword)
{
return find(&m_emptyRoot,keyword);
} TreeNode* Tree::find(TreeNode* parent,string& keyword)
{
string firstChar=keyword.substr(,PACE);
TreeNode* firstNode = parent->findChild(firstChar);
if(firstNode==NULL) //未找到
{
count=;
return NULL;
}
string restChar=keyword.substr(PACE,keyword.size());
if(firstNode->m_map.empty()) //对应词组结束,则判断该词为敏感词
{
//std::cout<<count+1<<endl;
return firstNode;
}
if(keyword.size()==PACE) //最后一个字
return NULL;
count++;
return find(firstNode,restChar);
}

Tree.cpp

最后就是利用上述的Tree来实现敏感词过滤,Filter::censor(string& source)函数用来进行敏感词过滤,source即输入的字符串,如果source包含敏感词,则用"**"代替掉。

Filter::load(const char* filePath)函数通过文件载入敏感词,并构建Tree。

为使实现简单,代码中过滤了英文数字及一些符号,让敏感词库的词能全部被识别。这里有2个问题遗留下来:

1.需要考虑英文,已经中英文结合的敏感词。程序还需要作出一定修改;

2.载入文件后,可对敏感词做出一定优化。

下面代码实现了Filter类,调用函数实现敏感词过滤。

 #include <string>
#include "Tree.h" class Filter
{
private:
Tree m_tree; public:
void load(const char* fileName);
bool m_initialized;
void censor(string& source);
};

Filter.h

 #include <iostream>
#include <fstream>
#include "Filter.h" void Filter::load(const char* filePath)
{
ifstream keywordsFile(filePath, ios::in);
if (keywordsFile.is_open())
{
char buffer[];
int count = ;
int offset = ;
while((buffer[offset]=keywordsFile.get())!=EOF)
{
if((buffer[offset]>='a'&&buffer[offset]<='z')||
(buffer[offset]>='A'&&buffer[offset]<='Z')||
(buffer[offset]>=''&&buffer[offset]<='')||
buffer[offset]=='\'')
continue;
string word1;
word1.assign(buffer,offset);
if(buffer[offset]==','&&(offset%)==)
{
string word;
if(offset)
{
word.assign(buffer,offset);
m_tree.insert(word);
}
offset = ;
}
else
offset++;
}
}
keywordsFile.close();
m_initialized = true;
} void Filter::censor(string& source)
{
if (!m_initialized)
{
cout<<"没有载入关键词";
return;
}
else
{
int length = source.size();
for (int i = ; i < length; i += )
{
string substring = source.substr(i, length - i);
if (m_tree.find(substring) != NULL) //发现敏感词
{
cout<<substring.substr(,(m_tree.count+)*)<<endl;
source.replace(i,(m_tree.count+)*,"**");
length = source.size();
}
}
}
}

Filter.cpp

最后就是调用Filter类,通过文件输入,并将过滤的结果输出到文件,并输出用时。

 #include<iostream>
#include<string>
#include<list>
#include <fstream>
#include "Filter.h"
#include <sys/timeb.h>
using namespace std; void main()
{
Filter filter;
string str;
filter.load("keywords.txt");
ifstream inputFile("input.txt",ios::in);
inputFile>>str;
inputFile.close();
ofstream outputFile("output.txt",ios::out);
struct timeb startTime,endTime;
ftime(&startTime);
for(int i=;i<;i++)
{
filter.censor(str);
}
ftime(&endTime);
cout<<str<<endl;
cout<<"查询用时:"<<(endTime.time-startTime.time)* +
(endTime.millitm - startTime.millitm)<<"ms"<<endl;
outputFile<<str<<endl;
outputFile<<"查询用时:"<<(endTime.time-startTime.time)* +
(endTime.millitm - startTime.millitm)<<"ms";
outputFile.close();
}

Process.cpp

最新文章

  1. jquery 设置页面元素不可点击、不可编辑、只读(备忘)
  2. C#创建datatable
  3. 如何在博客中插入jsfiddle的代码
  4. 【Winfrom】简单的焦点设置问题
  5. httpclient请求方法
  6. ExtJs4 SpringMvc3 实现Grid 分页
  7. 无责任Windows Azure SDK .NET开发入门篇三[使用Azure AD 管理用户信息--3.5 Delete删除用户]
  8. [Webpack 2] Chunking common modules from multiple apps with the Webpack CommonsChunkPlugin
  9. hdu3602(变形背包)
  10. log4cpp日志不能是溶液子体积
  11. 如何在阿里云linux上部署java项目
  12. Linux(CentOS6.5)下编译安装PHP5.6.22时报错&rdquo;configure: error: ZLIB extension requires gzgets in zlib&rdquo;的解决方式(确定已经编译安装Zlib,并已经指定Zlib路径)
  13. TCP和UDP
  14. js实现图片局部放大效果
  15. docker常用命令(自用)
  16. Linux系统根据端口号来查看其进程并杀死进程
  17. Dubbo高级篇4
  18. tls 流量画像——直接使用图像处理的思路探索,待进一步观察
  19. com_pc-mcu
  20. 教程 | 如何使用纯NumPy代码从头实现简单的卷积神经网络

热门文章

  1. java获取配置文件里面的内容
  2. XML中&amp; &lt;&gt; 单引号&#39; 双引号 &quot; 报错
  3. Emergency(山东省第一届ACM省赛)
  4. Google Developing for Android 一 - 相关上下文介绍
  5. android 绑定spinner键值对显示内存地址的问题
  6. JS中的split
  7. 如何为datagridview加上序号
  8. hive导入数据
  9. Linux SAMBA Practical
  10. swift 多线程及GCD