Rust文本内容过滤库rustrict的使用,rustrict提供高效敏感词检测与文本净化功能

Rust文本内容过滤库rustrict的使用,rustrict提供高效敏感词检测与文本净化功能

rustrict是一个Rust语言的高效敏感词过滤库,具有以下特点:

特性

  • 支持多种类型(亵渎、冒犯、性暗示、恶意、垃圾信息)
  • 多种严重级别(轻度、中度、严重)
  • 抗规避能力强(处理变体拼写、重复字符、混淆字符等)
  • 抗误判能力强
  • 灵活度高(支持多种输入方式和配置选项)
  • 性能优异(O(n)复杂度,不使用正则表达式)

使用示例

字符串过滤(&str)

use rustrict::CensorStr;

let censored: String = "hello crap".censor();
let inappropriate: bool = "f u c k".is_inappropriate();

assert_eq!(censored, "hello c***");
assert!(inappropriate);

迭代器过滤(Iterator<Item = char>)

use rustrict::CensorIter;

let censored: String = "hello crap".chars().censor().collect();

assert_eq!(censored, "hello c***");

高级用法

use rustrict::{Censor, Type};

let (censored, analysis) = Censor::from_str("123 Crap")
    .with_censor_threshold(Type::INAPPROPRIATE)
    .with_censor_first_character_threshold(Type::OFFENSIVE & Type::SEVERE)
    .with_ignore_false_positives(false)
    .with_ignore_self_censoring(false)
    .with_censor_replacement('*')
    .censor_and_analyze();

assert_eq!(censored, "123 C***");
assert!(analysis.is(Type::INAPPROPRIATE));
assert!(analysis.isnt(Type::PROFANE & Type::SEVERE | Type::SEXUAL));

检测规避行为

use rustrict::{CensorStr, Type};

// 检测用户是否试图规避过滤
assert!("pron".is(Type::EVASIVE));
assert!("porn".isnt(Type::EVASIVE));

// 只允许安全消息通过
assert!("Hello there!".is(Type::SAFE));
assert!("nice work.".is(Type::SAFE));
assert!("yes".is(Type::SAFE));
assert!("NVM".is(Type::SAFE));
assert!("gtg".is(Type::SAFE));
assert!("not a common phrase".isnt(Type::SAFE));

自定义敏感词(需要启用customize功能)

#[cfg(feature = "customize")]
{
    use rustrict::{add_word, CensorStr, Type};

    unsafe {
        add_word("reallyreallybadword", (Type::PROFANE & Type::SEVERE) | Type::MEAN);
        add_word("mybrandname", Type::SAFE);
    }
    
    assert!("Reallllllyreallllllybaaaadword".is(Type::PROFANE));
    assert!("MyBrandName".is(Type::SAFE));
}

聊天上下文过滤(需要启用context功能)

#[cfg(feature = "context")]
{
    use rustrict::{BlockReason, Context};
    use std::time::Duration;
    
    pub struct User {
        context: Context,
    }
    
    let mut bob = User {
        context: Context::default()
    };
    
    // 正常消息直接通过
    assert_eq!(bob.context.process(String::from("hello")), Ok(String::from("hello")));
    
    // 敏感词被过滤
    assert_eq!(bob.context.process(String::from("crap")), Ok(String::from("c***")));

    // 处理用户举报
    for _ in 0..5 {
        bob.context.report();
    }
   
    // 多次违规后,过滤更严格
    assert_eq!(bob.context.process(String::from("crap")), Ok(String::from("****")));
    
    // 手动禁言
    bob.context.mute_for(Duration::from_secs(2));
    assert!(matches!(bob.context.process(String::from("anything")), Err(BlockReason::Muted(_))));
}

完整示例代码

// 完整示例:使用rustrict进行敏感词检测和过滤
use rustrict::{CensorStr, Type};

fn main() {
    // 基本过滤
    let text = "This is some inappropriate content with bad words like shit and damn.";
    let censored = text.censor();
    println!("过滤后的文本: {}", censored);
    
    // 检查文本是否包含不当内容
    if text.is_inappropriate() {
        println!("警告: 文本包含不当内容!");
    }
    
    // 高级分析
    let analysis = Censor::from_str(text)
        .with_censor_replacement('#')
        .analyze();
    
    println!("分析结果:");
    println!("是否亵渎: {}", analysis.is(Type::PROFANE));
    println!("是否冒犯: {}", analysis.is(Type::OFFENSIVE));
    println!("是否严重: {}", analysis.is(Type::SEVERE));
    
    // 自定义过滤
    #[cfg(feature = "customize")]
    {
        unsafe {
            rustrict::add_word("rustisawesome", Type::SAFE);
            rustrict::add_word("hateyou", Type::MEAN);
        }
        
        println!("自定义词检测:");
        println!("'rustisawesome'是否安全: {}", "rustisawesome".is(Type::SAFE));
        println!("'hateyou'是否恶意: {}", "hateyou".is(Type::MEAN));
    }
    
    // 上下文过滤示例
    #[cfg(feature = "context")]
    {
        use std::time::Duration;
        
        let mut ctx = rustrict::Context::default();
        
        println!("\n上下文过滤测试:");
        println!("第一次: {:?}", ctx.process(String::from("crap")));
        println!("第二次: {:?}", ctx.process(String::from("damn")));
        
        // 多次举报后过滤更严格
        for _ in 0..5 { ctx.report(); }
        println!("举报后: {:?}", ctx.process(String::from("crap")));
        
        // 禁言测试
        ctx.mute_for(Duration::from_secs(2));
        println!("禁言中: {:?}", ctx.process(String::from("hello")));
    }
}

性能比较

与其他Rust敏感词过滤库相比,rustrict在准确性和性能方面表现优异:

库名称 准确率 阳性准确率 阴性准确率 处理时间
rustrict 80.00% 94.01% 76.50% 9s
censor 76.16% 72.76% 77.01% 23s
stfu 91.74% 77.69% 95.25% 45s
profane-rs 80.47% 73.79% 82.14% 52s

rustrict是一个功能强大、性能优异的文本过滤解决方案,特别适合需要高效内容审核的应用场景。


1 回复

Rust文本内容过滤库rustrict的使用指南

概述

rustrict是一个高效的Rust文本内容过滤库,专门用于敏感词检测和文本净化。它提供了多种过滤策略和配置选项,可以帮助开发者快速实现内容安全功能。

主要特性

  • 高效的敏感词检测算法
  • 支持多种过滤策略(替换、标记、完全删除等)
  • 可定制的敏感词列表
  • 支持大小写不敏感匹配
  • 低内存占用和高性能

安装方法

在Cargo.toml中添加依赖:

[dependencies]
rustrict = "0.4"

基本使用方法

1. 简单检测

use rustrict::CensorStr;

fn main() {
    let text = "This is a bad word example.";
    if text.is_inappropriate() {
        println!("文本包含不合适内容");
    } else {
        println!("文本内容正常");
    }
}

2. 文本净化

use rustrict::CensorStr;

fn main() {
    let text = "This is a bad word example.";
    let clean_text = text.censor();
    println!("净化后的文本: {}", clean_text);
    // 输出: "This is a *** word example."
}

3. 自定义过滤级别

use rustrict::{CensorStr, Type};

fn main() {
    let text = "Some mild profanity here.";
    let strict_text = text.censor_with_style(Type::SEVERE);
    println!("严格过滤: {}", strict_text);
}

高级功能

1. 添加自定义敏感词

use rustrict::Censor;

fn main() {
    let mut censor = Censor::new();
    censor.add_word("customword", rustrict::Type::INFORMAL);
    
    let text = "This contains customword.";
    println!("{}", censor.censor(&text));
    // 输出: "This contains **********."
}

2. 多种过滤策略

use rustrict::{Censor, Type, Replacement};

fn main() {
    let mut censor = Censor::new();
    censor.set_replacement(Replacement::Stars); // 使用星号替换
    
    let text = "Bad language here.";
    println!("{}", censor.censor(&text));
    
    censor.set_replacement(Replacement::Remove); // 完全删除敏感词
    println!("{}", censor.censor(&text));
}

3. 分析文本

use rustrict::CensorStr;

fn main() {
    let text = "This text has some questionable content.";
    let analysis = text.analyze();
    
    println!("文本分析结果:");
    println!("- 是否不合适: {}", analysis.is_inappropriate());
    println!("- 检测到的类型: {:?}", analysis.types_found());
    println!("- 原始风险评分: {}", analysis.raw_risk_score());
}

性能建议

对于需要处理大量文本的场景,建议创建并重用Censor实例:

use rustrict::Censor;

fn main() {
    let censor = Censor::new();
    
    // 处理多个文本
    let texts = vec![
        "First text to check",
        "Second text with potential issues",
        "Third harmless text"
    ];
    
    for text in texts {
        println!("{}", censor.censor(text));
    }
}

完整示例

use rustrict::{Censor, CensorStr, Type, Replacement};

fn main() {
    // 示例1: 简单检测
    let text1 = "This is a bad word example.";
    println!("--- 简单检测 ---");
    if text1.is_inappropriate() {
        println!("检测结果: 文本包含不合适内容");
    } else {
        println!("检测结果: 文本内容正常");
    }

    // 示例2: 文本净化
    let text2 = "This is a bad word example.";
    println!("\n--- 文本净化 ---");
    println!("原始文本: {}", text2);
    println!("净化文本: {}", text2.censor());

    // 示例3: 自定义过滤级别
    let text3 = "Some mild profanity here.";
    println!("\n--- 自定义过滤级别 ---");
    println!("严格过滤: {}", text3.censor_with_style(Type::SEVERE));

    // 示例4: 添加自定义敏感词
    let mut censor = Censor::new();
    censor.add_word("customword", Type::INFORMAL);
    let text4 = "This contains customword.";
    println!("\n--- 自定义敏感词 ---");
    println!("过滤结果: {}", censor.censor(&text4));

    // 示例5: 多种过滤策略
    println!("\n--- 多种过滤策略 ---");
    let mut censor2 = Censor::new();
    censor2.set_replacement(Replacement::Stars);
    let text5 = "Bad language here.";
    println!("星号替换: {}", censor2.censor(&text5));
    
    censor2.set_replacement(Replacement::Remove);
    println!("完全删除: {}", censor2.censor(&text5));

    // 示例6: 分析文本
    let text6 = "This text has some questionable content.";
    println!("\n--- 文本分析 ---");
    let analysis = text6.analyze();
    println!("是否不合适: {}", analysis.is_inappropriate());
    println!("检测类型: {:?}", analysis.types_found());
    println!("风险评分: {}", analysis.raw_risk_score());

    // 示例7: 性能优化 - 重用实例
    println!("\n--- 性能优化 ---");
    let censor3 = Censor::new();
    let texts = vec![
        "First text to check",
        "Second text with potential issues",
        "Third harmless text"
    ];
    for text in texts {
        println!("过滤结果: {}", censor3.censor(text));
    }
}

注意事项

  1. rustrict默认包含英文敏感词库,如需其他语言支持需要自行添加词库
  2. 过滤效果取决于敏感词库的完整性
  3. 对于关键应用场景,建议结合人工审核

rustrict是一个轻量级但功能强大的库,适合需要内容过滤的各种Rust应用场景,从聊天应用到内容管理系统都可以使用。

回到顶部