首页 > 其他分享 >基于profanity-check实现不文明用语识别和斗殴行为预测

基于profanity-check实现不文明用语识别和斗殴行为预测

时间:2024-06-14 11:02:11浏览次数:10  
标签:文明用语 chinese profanity blacklist words text check

一、语音识别不文明用语

1.1、语言检查库profanity-check

这是一个快速、强大的Python库,用于检测字符串中的不雅或冒犯性语言。更多关于profanity-check如何构建以及为何要构建它的信息可在这篇博客文章中找到。

1.2、测试模型

运行环境:

python                   3.8.19

jieba                    0.42.1

numpy                    1.20.0

scikit-learn             0.22.2

profanity-check          1.0.3

这是一个简单的示例

import joblib
from profanity_check import predict_prob
import jieba
# 自定义的中文黑名单词语
chinese_blacklist = {'卧槽', '屌', 'TM'}
def contains_profanity(text, chinese_blacklist):
    # 使用jieba进行中文分词
    words = set(jieba.lcut(text))
    # 检查分词后的词语是否在自定义黑名单中
    if any(word in chinese_blacklist for word in words):
        return True
    # 使用profanity-check库进行中文不文明用语检测
    try:
        prediction = predict_prob([text])[0]
        if prediction > 0.5:  # 使用预测概率来判断是否含有不文明用语
            return True
    except Exception as e:
        print(f"Error predicting profanity in text: {text}")
        print(e)
    return False
# 测试文本
texts = [
    "卧槽,什么屌玩意这么贵。",
    "嫌贵你TM不买。",
    "不买了,你家卖的真贵"
]
for text in texts:
    if contains_profanity(text, chinese_blacklist):
        print(f"'{text}' 此句有不文明用语")
    else:
        print(f"'{text}' 此句用语文明")

结果:根据结果可以看到输入的三段话被准确的识别出来了

1.3、读取自定义的中文黑名单词语

创建自定义的中文黑名单txt文件,在正式环境中应当放置在MySQL服务器上构建自定义中文黑名单库

uncivilized_words.txt

以下是一个简单的示例

import joblib
from profanity_check import predict_prob
import jieba
# 从文件读取中文黑名单词语
def load_chinese_blacklist(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        blacklist = set([word.strip() for word in file.readlines()])
    return blacklist
def contains_profanity(text, chinese_blacklist):
    # 使用jieba进行中文分词
    words = set(jieba.lcut(text))
    # 检查分词后的词语是否在自定义黑名单中
    if any(word in chinese_blacklist for word in words):
        return True
    # 使用profanity-check库进行中文不文明用语检测
    try:
        prediction = predict_prob([text])[0]
        if prediction > 0.5:  # 使用预测概率来判断是否含有不文明用语
            return True
    except Exception as e:
        print(f"Error predicting profanity in text: {text}")
        print(e)
    return False
# 从文件加载自定义的中文黑名单词语
chinese_blacklist = load_chinese_blacklist('/home/myj/uncivilized_words.txt')
# 测试文本
texts = [
    "卧槽,什么屌玩意这么贵。",
    "嫌贵你TM不买。",
    "不买了,你家卖的真贵"
]
for text in texts:
    if contains_profanity(text, chinese_blacklist):
        print(f"'{text}' 此句有不文明用语")
    else:
        print(f"'{text}' 此句用语文明")

结果

1.4、识别出不文明用语词

contains_profanity 函数:分词处理:使用 jieba.lcut 对输入文本 text 进行分词。

不文明词汇检测:遍历分词后的词汇列表,检查每个词语是否存在于 chinese_blacklist 中。如果存在,则将该不文明词语添加到 profane_words 列表中。

中文不文明词汇检测:尝试使用 profanity-check 库对整段文本进行检测。如果检测的概率超过 0.5(表示可能包含不文明用语),则将整个文本视为不文明,并添加到 profane_words 列表中。

返回结果:返回包含所有检测到的不文明词汇的列表。

主程序逻辑:从指定路径加载自定义的中文不文明词汇列表。遍历测试文本列表,对每个文本调用 contains_profanity 函数。根据返回的结果,打印出包含不文明词汇的文本以及具体的不文明词语。

import joblib
from profanity_check import predict_prob
import jieba
# 从文件读取中文黑名单词语
def load_chinese_blacklist(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        blacklist = set([word.strip() for word in file.readlines()])
    return blacklist
def contains_profanity(text, chinese_blacklist):
    # 使用jieba进行中文分词
    words = jieba.lcut(text)
    # 检查分词后的词语是否在自定义黑名单中,收集不文明词汇
    profane_words = [word for word in words if word in chinese_blacklist]
    # 使用profanity-check库进行中文不文明用语检测
    try:
        prediction = predict_prob([text])[0]
        if prediction > 0.5:  # 使用预测概率来判断是否含有不文明用语
            profane_words.append(text)  # 如果检测到整个文本为不文明,就将其添加到结果中
    except Exception as e:
        print(f"Error predicting profanity in text: {text}")
        print(e)
    return profane_words
# 从文件加载自定义的中文黑名单词语
chinese_blacklist = load_chinese_blacklist('/home/myj/uncivilized_words.txt')
# 测试文本
texts = [
    "卧槽,什么屌玩意这么贵。",
    "嫌贵你TM不买。",
    "不买了,你家卖的真贵"
]
for text in texts:
    profane_words = contains_profanity(text, chinese_blacklist)
    if profane_words:
        print(f"'{text}' 此句有不文明用语: {', '.join(profane_words)}")
    else:
        print(f"'{text}' 此句用语文明")

结果

为了方便观察分词结果,提供以下代码

从指定路径加载自定义的中文不文明词汇列表。遍历测试文本列表,对每个文本调用 contains_profanity 函数。根据返回的结果,打印出包含不文明词汇的文本以及具体的不文明词语,并打印出相应句子的分词结果。

import joblib
from profanity_check import predict_prob
import jieba
# 从文件读取中文黑名单词语
def load_chinese_blacklist(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        blacklist = set([word.strip() for word in file.readlines()])
    return blacklist
def contains_profanity(text, chinese_blacklist):
    # 使用jieba进行中文分词
    words = jieba.lcut(text)
    # 检查分词后的词语是否在自定义黑名单中,收集不文明词汇
    profane_words = [word for word in words if word in chinese_blacklist]
    # 使用profanity-check库进行英文不文明用语检测
    try:
        prediction = predict_prob([text])[0]
        if prediction > 0.5:  # 使用预测概率来判断是否含有不文明用语
            profane_words.append(text)  # 如果检测到整个文本为不文明,就将其添加到结果中
    except Exception as e:
        print(f"Error predicting profanity in text: {text}")
        print(e)
    return words, profane_words
# 从文件加载自定义的中文黑名单词语
chinese_blacklist = load_chinese_blacklist('/home/myj/uncivilized_words.txt')
# 测试文本
texts = [
    "卧槽,什么屌玩意这么贵。",
    "嫌贵你TM不买。",
    "不买了,你家卖的真贵"
]
for text in texts:
    words, profane_words = contains_profanity(text, chinese_blacklist)
    if profane_words:
        print(f"'{text}' 此句有不文明用语: {', '.join(profane_words)}")
    else:
        print(f"'{text}' 此句用语文明")
    print("断词结果:", ", ".join(words))

结果

下一章,将根据上述测试的结果,识别出的谩骂行为的基础上识别出对骂的行为,后续结合大模型针对文本进行情感分析,认定为消极情绪,且有辱骂行为的,应当认定为可能发生斗殴行为。

二、对语音识别出的谩骂词进行斗殴行为预测

2.1、下载StructBERT情感分类模型库

本次使用到的模型为:StructBERT情感分类-中文-通用-base

iic/nlp_structbert_sentiment-classification_chinese-base

测试代码如下:

from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
# 模型目录路径
model_directory = "/home/myj/nlp_structbert_sentiment-classification_chinese-base"
# 加载模型
nlp_pipeline = pipeline(Tasks.sentiment_classification, model=model_directory)
# 准备测试文本
texts = [
    "卧槽,什么屌玩意这么贵。",
    "嫌贵你TM不买。",
    "不买了,你家卖的真贵"
]
# 推理并输出结果
for text in texts:
    result = nlp_pipeline(text)
    print(f"Text: {text}")
    print(result)  # 打印整个返回结果以查看结构

结果:

2.2、根据1.4中的代码结合调用StructBERT模型

代码逻辑如下:

1、load_chinese_blacklist 函数用于从文件中加载自定义的中文黑名单词语,并返回一个集合。

2、contains_profanity 函数接收一个文本和中文黑名单词语集合作为参数,使用分词工具 jieba 对文本进行中文分词,然后检查分词后的词语是否在自定义黑名单中,收集不文明词汇。接着使用 profanity-check 库对英文不文明用语进行检测,根据预测结果判断是否含有不文明用语,并将检测到的不文明词汇添加到结果中。

3、predict_emotion 函数接收文本和情感分类模型作为参数,使用情感分类模型进行预测,并返回情感标签。

4、加载自定义的中文黑名单词语和情感分类模型。

5、对测试文本列表中的每个文本进行处理:首先检查是否包含不文明用语,如果包含则预测情感,最后输出结果,说明该句子是否有不文明用语、情绪是否激动,以及是否有可能导致打架。

整体逻辑是从加载自定义黑名单词语和情感分类模型开始,依次对文本进行处理并输出结果。这段代码的目的是检测文本中的不文明用语,并根据情感分类模型判断情绪状况。

配置环境如下:

着重注意numpy和pandas的版本。

python -V                3.8.19

jieba                    0.42.1

joblib                   1.4.2

modelscope               1.15.0

numpy                    1.20.3

pandas                   2.0.0

profanity-check          1.0.3

scikit-learn             0.22.2

torch                    2.3.1

torchaudio               2.3.1

torchvision              0.18.1

transformers             4.41.2

代码示例如下

import joblib
from profanity_check import predict_prob
import jieba
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
# 从文件读取中文黑名单词语
def load_chinese_blacklist(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        blacklist = set([word.strip() for word in file.readlines()])
    return blacklist
def contains_profanity(text, chinese_blacklist):
    # 使用jieba进行中文分词
    words = jieba.lcut(text)
    # 检查分词后的词语是否在自定义黑名单中,收集不文明词汇
    profane_words = [word for word in words if word in chinese_blacklist]
    # 使用profanity-check库进行英文不文明用语检测
    try:
        prediction = predict_prob([text])[0]
        if prediction > 0.5:  # 使用预测概率来判断是否含有不文明用语
            profane_words.append(text)  # 如果检测到整个文本为不文明,就将其添加到结果中
    except Exception as e:
        print(f"Error predicting profanity in text: {text}")
        print(e)
    return profane_words
def predict_emotion(text, model):
    # 使用情感分类模型进行预测
    result = model(text)
    scores = result['scores']
    labels = result['labels']
    max_score_index = scores.index(max(scores))
    sentiment_label = labels[max_score_index]
    return sentiment_label
# 从文件加载自定义的中文黑名单词语
chinese_blacklist = load_chinese_blacklist('/home/myj/uncivilized_words.txt')
# 加载情感分类模型
model_directory = "/home/myj/nlp_structbert_sentiment-classification_chinese-base"
nlp_pipeline = pipeline(Tasks.sentiment_classification, model=model_directory)
# 测试文本
texts = [
    "卧槽,什么屌玩意这么贵。",
    "嫌贵你TM不买。",
    "不买了,你家卖的真贵"
]
for text in texts:
    profane_words = contains_profanity(text, chinese_blacklist)
    if profane_words:
        emotion = predict_emotion(text, nlp_pipeline)
        if emotion == '负面':  # 根据模型的输出,判断是否情绪激动
            print(f"'{text}' 此句有不文明用语且情绪激动,可能存在打架的可能性")
        else:
            print(f"'{text}' 此句有不文明用语但情绪较平静")
    else:
        print(f"'{text}' 此句用语文明")

结果:

2.3、基于TextBlob库轻量级识别斗殴可能

介绍:

TextBlob是一个基于NLTK和Pattern库的Python库,用于处理自然语言文本处理任务。它提供了简单且易于使用的API,用于进行文本情感分析、词形还原、名词短语提取、词性标注、拼写纠正等常见的文本处理任务。

代码逻辑如下:

定义函数 load_chinese_blacklist,从给定文件路径读取中文黑名单词语,存入一个集合中,以便快速查找。

检测文本中的不文明用语:定义函数 contains_profanity 接受文本和中文黑名单词语作为参数。使用 jieba 对文本进行分词,然后检查这些词语是否存在于中文黑名单中,若存在则收集这些不文明词汇。使用 profanity_check 库来检测英文不文明用语。如果预测概率超过0.5,则认为存在不文明用语,将整个文本加入不文明词汇列表中。返回检测到的不文明用语列表。

情感分析:定义函数 check_sentiment_for_fight,使用 TextBlob 检查文本的情感极性分数,如果分数小于0,表示负面情感,并返回 True。定义函数 get_sentiment_label,使用 TextBlob 计算情感极性分数,并根据分数返回对应的情绪标签(正面、负面、中性)。

主程序逻辑:

从文件中加载自定义的中文黑名单词语。

定义一个包含要分析文本的列表 texts。

遍历每个文本,依次进行不文明用语检测和情感分析。

根据不文明用语和情感分析结果,打印相应的提示信息和情绪标签。

版本:

textblob                 0.18.0.post0

代码示例如下

# 导入必要的库
from textblob import TextBlob
import joblib
from profanity_check import predict_prob
import jieba
# 定义函数从文件读取中文黑名单词语
def load_chinese_blacklist(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        blacklist = set([word.strip() for word in file.readlines()])
    return blacklist
# 定义函数检测文本是否包含不文明用语
def contains_profanity(text, chinese_blacklist):
    words = jieba.lcut(text)  # 使用jieba进行中文分词
    profane_words = [word for word in words if word in chinese_blacklist]  # 检查词语是否在黑名单中
    try:
        prediction = predict_prob([text])[0]  # 使用profanity-check库进行英文不文明用语检测
        if prediction > 0.5:  # 如果检测到不文明用语
            profane_words.append(text)  # 将整个文本加入不文明词汇列表
    except Exception as e:
        print(f"Error predicting profanity in text: {text}")
        print(e)
    return profane_words  # 返回不文明用语列表
# 从文件加载自定义的中文黑名单词语
chinese_blacklist = load_chinese_blacklist('/home/myj/uncivilized_words.txt')
# 定义函数检查文本的情感极性分数是否为负面
def check_sentiment_for_fight(text):
    blob = TextBlob(text)
    sentiment_score = blob.sentiment.polarity
    return sentiment_score < 0  # 返回布尔值表示是否为负面情感
# 定义函数获取文本的情绪标签
def get_sentiment_label(text):
    blob = TextBlob(text)
    sentiment_score = blob.sentiment.polarity
    if sentiment_score > 0:
        return "正面"
    elif sentiment_score < 0:
        return "负面"
    else:
        return "中性"
# 要分析的文本列表
texts = [
    "卧槽,什么屌玩意这么贵。",
    "嫌贵你TM不买。",
    "不买了,你家卖的真贵"
]
# 遍历每个文本,检测不文明用语并进行情感分析
for text in texts:
    profane_words = contains_profanity(text, chinese_blacklist)
    has_negative_sentiment = check_sentiment_for_fight(text)
    sentiment_label = get_sentiment_label(text)
    if profane_words and has_negative_sentiment:
        print(f"'{text}' 此句有不文明用语且存在打架的可能性: {', '.join(profane_words)}")
    elif profane_words:
        print(f"'{text}' 此句有不文明用语: {', '.join(profane_words)}")
    elif has_negative_sentiment:
        print(f"'{text}' 此句可能存在打架的可能性")
    else:
        print(f"'{text}' 此句用语文明")
    print(f"情绪分析:{sentiment_label}")

结果:

总结:对比2.2和2.3,大模型有不文明用语或者说话语气重一点就有打架冲突,而textblob库分析出来属于中性。

标签:文明用语,chinese,profanity,blacklist,words,text,check
From: https://blog.csdn.net/weixin_72954236/article/details/139655444

相关文章

  • SFC(System File Checker)是Windows操作系统中的一个实用程序,用于扫描和修复受损或丢失
    SFC(SystemFileChecker)是Windows操作系统中的一个实用程序,用于扫描和修复受损或丢失的系统文件。以下是一些常见的SFC命令及其用途:sfc/scannow描述:扫描所有受保护的系统文件,并尽可能修复文件。用法:在命令提示符(以管理员身份运行)中输入 sfc/scannow。sfc/verifyon......
  • snmp-check一键获取SNMP信息(KALI工具系列二十一)
    目录1、KALILINUX简介  2、snmp-check工具简介3、在KALI中使用onesixtyone3.1目标主机IP(win)3.2KALI的IP 4、操作示例4.1SNMP检查4.2指定SNMP端口4.3指定社区字符串4.4详细输出4.5指定多项5、总结1、KALILINUX简介KaliLinux是一个功能强大......
  • 开源C++静态代码检测工具clang-tidy、cppcheck和oclint的比较
    以下是clang-tidy、cppcheck和oclint的比较关于Clang-Tidy的使用请参考:使用Clang-Tidy进行静态代码分析:完整的配置与CMake集成实例关于Cppcheck的使用请参考:使用Cppcheck进行静态代码分析:完整的shell脚本与CMake集成实例关于OCLint的使用请参考:使用OCLint......
  • Preview failedUnable to start the previewer. openPreviewerLog to check for detai
    DevEcostudio预览器报错 PreviewfailedUnabletostartthepreviewer.openPreviewerLogtocheckfordetails.有两种原因1.main_page.json     src下的路径是否重复        2.struct关键字声明自定义组件名称是否重复我自己排查出来的......
  • @firebase/app-check: FirebaseError: AppCheck: ReCAPTCHA 错误
    我在我的javascript网络应用程序中实施了AppCheckreCAPTCHAEnterprise流程。我遵循了文档中提到的所有步骤。在Firebase控制台中启用AppCheck,注册Web应用程序,并在GCP控制台中启用reCAPTCHAEnterpriseAPI。创建网站密钥,并在Firebase应用程序检查控制台中添加该......
  • 前端菜鸡流水账日记 -- checkbox二级菜单滚动条设置
    下午好哇,今天二更咯,这次想说的是一个ElemenuUI中的一个组件--checkbox多选框,管网的地址是https://element.eleme.cn/#/zh-CN/component/installation,关于这个的具体的写法,感兴趣的小伙伴可以去管网看看,很快就能找到的我今天要记录的是关于他的二级菜单当盒子的内容过多时,超......
  • 使用CRaC为JVM创建checkpoint
    CRaCCoordinatedRestoreatCheckpoint,缩写为CRaC,大致的原理是将JVM的当前运行状态进行持久化存储起来,再条件JDK版本:17及以上,建议17或21OpenJDK发行版,目前支持CRaC的JDK有两家:ZuluJDK:发行商为Azul,下载地址:https://www.azul.com/downloads/?version=java-17-lts&os=c......
  • SystemC & TLM-2.0 - TLM-2.0 Protocol Checker for SytemC
    InteroperabilityLayer&BaseProtocolthebaseprotocolisthekeyelementintheinteroperabilitylayerinTLMtonaughtwhichalsoconsistsofthecoreinterfacesstandardsocketsandthegenericpayloadsothebaseprotocolthat'sbeingcheck......
  • C# Parallel foreach Parallel Source array was not long enough. Check srcIndex an
    //Indexwasoutsidetheboundsofthearray.//Sourcearraywasnotlongenough.ChecksrcIndexandlength,andthearray'slowerbounds//usingSystem;usingSystem.Collections.Concurrent;usingSystem.Collections.Generic;usingSystem.Linq;usingSy......
  • PyQT5之Checkbox
    """复选框"""importos.pathfromPyQt5importQtWidgetsfromPyQt5importQtCore,QtGuiimportsysimportcv2classButtonPanel(QtWidgets.QWidget):def__init__(self,*args,**kwargs):super().__init__(*args,**k......