C++实现敏感词过滤(3) Filter类的实现

本文介绍了C++中Filter类的设计与实现,用于敏感词过滤。Filter类包含初始化、加载敏感词库和检查字符串是否包含敏感词的功能。通过Trie树结构,实现了高效的关键词查找,确保了敏感词的精确匹配。
摘要由CSDN通过智能技术生成

五.Filter类的定义:

Filter.h:

#include <string>

#include "Trie.h"

class Filter {

private:

static bool __initialized;

static Trie __trie;

static void load(const char* fileName, int startPos);

static bool censor(std::string& source);

public:

static bool __LEGAL;

static bool __ILLEGAL;

enum Level{

NORMAL = 1,

HIGH = 2

};

static void init(Level level,std::string loadFile = "");

static bool isInitialized();

static bool censor(const char* source, int length);

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
敏感词检测是一种文本过滤技术,可以通过对文本进行过滤来保护用户免受有害信息和不良言论的影响。下面是一个用C++实现敏感词检测的后端的示例代码: ```c++ #include <iostream> #include <string> #include <vector> #include <fstream> using namespace std; class TrieNode { public: TrieNode() { for (int i = 0; i < 26; i++) { next[i] = nullptr; } is_end = false; } TrieNode* next[26]; bool is_end; }; class TrieTree { public: TrieTree() { root = new TrieNode(); } void insert(string word) { TrieNode* p = root; for (char c : word) { if (p->next[c - 'a'] == nullptr) { p->next[c - 'a'] = new TrieNode(); } p = p->next[c - 'a']; } p->is_end = true; } bool search(string word) { TrieNode* p = root; for (char c : word) { if (p->next[c - 'a'] == nullptr) { return false; } p = p->next[c - 'a']; } return p->is_end; } bool startsWith(string prefix) { TrieNode* p = root; for (char c : prefix) { if (p->next[c - 'a'] == nullptr) { return false; } p = p->next[c - 'a']; } return true; } private: TrieNode* root; }; int main() { TrieTree tree; ifstream fin("sensitive_words.txt"); if (fin) { string line; while (getline(fin, line)) { tree.insert(line); } fin.close(); } string text; cout << "请输入文本:" << endl; getline(cin, text); vector<string> sensitive_words; for (int i = 0; i < text.length(); i++) { for (int j = 1; j <= 10 && i + j <= text.length(); j++) { string word = text.substr(i, j); if (tree.search(word)) { sensitive_words.push_back(word); } } } if (sensitive_words.empty()) { cout << "文本中没有敏感词。" << endl; } else { cout << "文本中的敏感词有:" << endl; for (string word : sensitive_words) { cout << word << endl; } } return 0; } ``` 上述代码主要使用了Trie树,通过将敏感词构建成Trie树,可以快速地进行检索。具体来说,首先从文件中读取敏感词并插入到Trie树中,然后对输入的文本进行遍历,每次取出一个长度为1到10之间的子串,在Trie树中查找是否存在该子串。如果存在,则将其添加到敏感词列表中。最后,输出敏感词列表即可。
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值