python实现过滤敏感词


Posted in Python onMay 08, 2021

简述:

关于敏感词过滤可以看成是一种文本反垃圾算法,例如
 题目:敏感词文本文件 filtered_words.txt,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」
 代码:

#coding=utf-8
def filterwords(x):
    with open(x,'r') as f:
        text=f.read()
    print text.split('\n')
    userinput=raw_input('myinput:')
    for i in text.split('\n'):
        if i in userinput:
            replace_str='*'*len(i.decode('utf-8'))
            word=userinput.replace(i,replace_str)
            return word

print filterwords('filtered_words.txt')

再例如反黄系列:

开发敏感词语过滤程序,提示用户输入评论内容,如果用户输入的内容中包含特殊的字符:
敏感词列表 li = ["苍老师","东京热",”武藤兰”,”波多野结衣”]
则将用户输入的内容中的敏感词汇替换成***,并添加到一个列表中;如果用户输入的内容没有敏感词汇,则直接添加到上述的列表中。
content = input('请输入你的内容:')
li = ["苍老师","东京热","武藤兰","波多野结衣"]
i = 0
while i < 4:
    for li[i] in content:
        li1 = content.replace('苍老师','***')
        li2 = li1.replace('东京热','***')
        li3 = li2.replace('武藤兰','***')
        li4 = li3.replace('波多野结衣','***')
    else:
        pass
    i += 1

python实现过滤敏感词

实战案例:

 一道bat面试题:快速替换10亿条标题中的5万个敏感词,有哪些解决思路?
 有十亿个标题,存在一个文件中,一行一个标题。有5万个敏感词,存在另一个文件。写一个程序过滤掉所有标题中的所有敏感词,保存到另一个文件中。

1、DFA过滤敏感词算法

在实现文字过滤的算法中,DFA是比较好的实现算法。DFA即Deterministic Finite Automaton,也就是确定有穷自动机。
 算法核心是建立了以敏感词为基础的许多敏感词树。
 python 实现DFA算法:

# -*- coding:utf-8 -*-

import time
time1=time.time()

# DFA算法
class DFAFilter():
    def __init__(self):
        self.keyword_chains = {}
        self.delimit = '\x00'

    def add(self, keyword):
        keyword = keyword.lower()
        chars = keyword.strip()
        if not chars:
            return
        level = self.keyword_chains
        for i in range(len(chars)):
            if chars[i] in level:
                level = level[chars[i]]
            else:
                if not isinstance(level, dict):
                    break
                for j in range(i, len(chars)):
                    level[chars[j]] = {}
                    last_level, last_char = level, chars[j]
                    level = level[chars[j]]
                last_level[last_char] = {self.delimit: 0}
                break
        if i == len(chars) - 1:
            level[self.delimit] = 0

    def parse(self, path):
        with open(path,encoding='utf-8') as f:
            for keyword in f:
                self.add(str(keyword).strip())

    def filter(self, message, repl="*"):
        message = message.lower()
        ret = []
        start = 0
        while start < len(message):
            level = self.keyword_chains
            step_ins = 0
            for char in message[start:]:
                if char in level:
                    step_ins += 1
                    if self.delimit not in level[char]:
                        level = level[char]
                    else:
                        ret.append(repl * step_ins)
                        start += step_ins - 1
                        break
                else:
                    ret.append(message[start])
                    break
            else:
                ret.append(message[start])
            start += 1

        return ''.join(ret)


if __name__ == "__main__":
    gfw = DFAFilter()
    path="F:/文本反垃圾算法/sensitive_words.txt"
    gfw.parse(path)
    text="新疆骚乱苹果新品发布会?八"
    result = gfw.filter(text)

    print(text)
    print(result)
    time2 = time.time()
    print('总共耗时:' + str(time2 - time1) + 's')

运行效果:

新疆骚乱苹果新品发布会?八
****苹果新品发布会**
总共耗时:0.0010344982147216797s

2、AC自动机过滤敏感词算法

AC自动机:一个常见的例子就是给出n个单词,再给出一段包含m个字符的文章,让你找出有多少个单词在文章里出现过。
 简单地讲,AC自动机就是字典树+kmp算法+失配指针

# -*- coding:utf-8 -*-

import time
time1=time.time()

# AC自动机算法
class node(object):
    def __init__(self):
        self.next = {}
        self.fail = None
        self.isWord = False
        self.word = ""

class ac_automation(object):

    def __init__(self):
        self.root = node()

    # 添加敏感词函数
    def addword(self, word):
        temp_root = self.root
        for char in word:
            if char not in temp_root.next:
                temp_root.next[char] = node()
            temp_root = temp_root.next[char]
        temp_root.isWord = True
        temp_root.word = word

    # 失败指针函数
    def make_fail(self):
        temp_que = []
        temp_que.append(self.root)
        while len(temp_que) != 0:
            temp = temp_que.pop(0)
            p = None
            for key,value in temp.next.item():
                if temp == self.root:
                    temp.next[key].fail = self.root
                else:
                    p = temp.fail
                    while p is not None:
                        if key in p.next:
                            temp.next[key].fail = p.fail
                            break
                        p = p.fail
                    if p is None:
                        temp.next[key].fail = self.root
                temp_que.append(temp.next[key])

    # 查找敏感词函数
    def search(self, content):
        p = self.root
        result = []
        currentposition = 0

        while currentposition < len(content):
            word = content[currentposition]
            while word in p.next == False and p != self.root:
                p = p.fail

            if word in p.next:
                p = p.next[word]
            else:
                p = self.root

            if p.isWord:
                result.append(p.word)
                p = self.root
            currentposition += 1
        return result

    # 加载敏感词库函数
    def parse(self, path):
        with open(path,encoding='utf-8') as f:
            for keyword in f:
                self.addword(str(keyword).strip())

    # 敏感词替换函数
    def words_replace(self, text):
        """
        :param ah: AC自动机
        :param text: 文本
        :return: 过滤敏感词之后的文本
        """
        result = list(set(self.search(text)))
        for x in result:
            m = text.replace(x, '*' * len(x))
            text = m
        return text





if __name__ == '__main__':

    ah = ac_automation()
    path='F:/文本反垃圾算法/sensitive_words.txt'
    ah.parse(path)
    text1="新疆骚乱苹果新品发布会?八"
    text2=ah.words_replace(text1)

    print(text1)
    print(text2)

    time2 = time.time()
    print('总共耗时:' + str(time2 - time1) + 's')

运行结果:

新疆骚乱苹果新品发布会?八
****苹果新品发布会**
总共耗时:0.0010304450988769531s

以上就是python实现过滤敏感词的详细内容,更多关于python 过滤敏感词的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
Python中一些自然语言工具的使用的入门教程
Apr 13 Python
在Python中使用PIL模块处理图像的教程
Apr 29 Python
Python的Flask框架中的Jinja2模板引擎学习教程
Jun 30 Python
Python多线程经典问题之乘客做公交车算法实例
Mar 22 Python
将TensorFlow的模型网络导出为单个文件的方法
Apr 23 Python
python实现画一颗树和一片森林
Jun 25 Python
在python中只选取列表中某一纵列的方法
Nov 28 Python
Python实现的删除重复文件或图片功能示例【去重】
Apr 23 Python
python文件绝对路径写法介绍(windows)
Dec 25 Python
基于Tensorflow批量数据的输入实现方式
Feb 05 Python
Python threading.local代码实例及原理解析
Mar 16 Python
python基础入门之普通操作与函数(三)
Jun 13 Python
Django中的JWT身份验证的实现
May 07 #Python
python开发实时可视化仪表盘的示例
Python使用scapy模块发包收包
如何用 Python 子进程关闭 Excel 自动化中的弹窗
PyTorch的Debug指南
May 07 #Python
基于Python的EasyGUI学习实践
Python列表删除重复元素与图像相似度判断及删除实例代码
You might like
PHP的ASP防火墙
2006/10/09 PHP
PHP下10件你也许并不了解的事情
2008/09/11 PHP
浅析PHP的ASCII码转换类
2013/07/05 PHP
PHP 输出URL的快捷方式示例代码
2013/09/22 PHP
PHP+AJAX 投票器功能
2017/11/11 PHP
php nginx 实时输出的简单实现方法
2018/01/21 PHP
javascript学习笔记(五)正则表达式
2011/04/08 Javascript
文字溢出实现溢出的部分再放入一个新生成的div中具体代码
2013/05/17 Javascript
JS获取鼠标坐标的实例方法
2013/07/18 Javascript
如何学习Javascript入门指导
2013/11/01 Javascript
Jquery获取和修改img的src值的方法
2014/02/17 Javascript
js实现下拉列表选中某个值的方法(3种方法)
2015/12/17 Javascript
漫谈JS引擎的运行机制 你应该知道什么
2016/06/15 Javascript
利用css+原生js制作简单的钟表
2020/04/07 Javascript
从零开始学习Node.js系列教程一:http get和post用法分析
2017/04/13 Javascript
JavaScript箭头(arrow)函数详解
2017/06/04 Javascript
jQuery判断网页是否已经滚动到浏览器底部的实现方法
2017/10/27 jQuery
vue学习笔记之slot插槽基本用法实例分析
2020/02/01 Javascript
react 生命周期实例分析
2020/05/18 Javascript
vue-列表下详情的展开与折叠案例
2020/07/28 Javascript
关于python的bottle框架跨域请求报错问题的处理方法
2017/03/19 Python
Django 生成登陆验证码代码分享
2017/12/12 Python
python+matplotlib绘制饼图散点图实例代码
2018/01/20 Python
python3+PyQt5 使用三种不同的简便项窗口部件显示数据的方法
2019/06/17 Python
Django分页功能的实现代码详解
2019/07/29 Python
Pytorch根据layers的name冻结训练方式
2020/01/06 Python
TensorFLow 不同大小图片的TFrecords存取实例
2020/01/20 Python
python如何建立全零数组
2020/07/19 Python
CSS3截取字符串实例代码【推荐】
2018/06/07 HTML / CSS
美国婴儿用品及配件购买网站:Munchkin
2019/04/03 全球购物
C#的几个面试问题
2016/05/22 面试题
外贸公司实习自我鉴定
2013/09/24 职场文书
一份报关员的职业规划范文
2014/01/08 职场文书
2016年大学生暑期社会实践方案
2015/11/26 职场文书
2016党员三严三实心得体会
2016/01/15 职场文书
婚前协议书怎么写,才具有法律效力呢 ?
2019/06/28 职场文书