python用类实现文章敏感词的过滤方法示例

作者:代序春秋 时间:2022-04-10 19:30:25 

过滤一遍并将敏感词替换之后剩余字符串中新组成了敏感词语,这种情况就要用递归来解决,直到过滤替换之后的结果和过滤之前一样时才算结束

第一步:建立一个敏感词库(.txt文本)

python用类实现文章敏感词的过滤方法示例

第二步:编写代码在文章中过滤敏感词(递归实现)


# -*- coding: utf-8 -*-
# author 代序春秋
import os
import chardet

# 获取文件目录和绝对路径
curr_dir = os.path.dirname(os.path.abspath(__file__))
# os.path.join()拼接路径
sensitive_word_stock_path = os.path.join(curr_dir, 'sensitive_word_stock.txt')

# 获取存放敏感字库的路径
# print(sensitive_word_stock_path)

class ArticleFilter(object):
 # 实现文章敏感词过滤
 def filter_replace(self, string):
   # string = string.decode("gbk")
   #  存放敏感词的列表
   filtered_words = []
   #  打开敏感词库读取敏感字
   with open(sensitive_word_stock_path) as filtered_words_txt:
     lines = filtered_words_txt.readlines()
     for line in lines:
       # strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
       filtered_words.append(line.strip())
   # 输出过滤好之后的文章
   print("过滤之后的文字:" + self.replace_words(filtered_words, string))

# 实现敏感词的替换,替换为*
 def replace_words(self, filtered_words, string):
   #  保留新字符串
   new_string = string
   #  从列表中取出敏感词
   for words in filtered_words:
     # 判断敏感词是否在文章中
     if words in string:
       # 如果在则用*替换(几个字替换几个*)
       new_string = string.replace(words, "*" * len(words))
   # 当替换好的文章(字符串)与被替换的文章(字符串)相同时,结束递归,返回替换好的文章(字符串)
   if new_string == string:
     #  返回替换好的文章(字符串)
     return new_string
   # 如果不相同则继续替换(递归函数自己调用自己)
   else:
     #  递归函数自己调用自己
     return self.replace_words(filtered_words, new_string)

def main():
 while True:
   string = input("请输入一段文字:")
   run = ArticleFilter()
   run.filter_replace(string)
   continue

if __name__ == '__main__':
 main()

运行结果:

python用类实现文章敏感词的过滤方法示例

来源:https://blog.csdn.net/geek64581/article/details/102750552

标签:python,敏感词,过滤
0
投稿

猜你喜欢

  • 详解python之heapq模块及排序操作

    2023-10-14 04:55:20
  • pytorch实现textCNN的具体操作

    2022-08-28 17:40:00
  • Ubuntu Server 11.10安装配置lamp(Apache+MySQL+PHP)

    2023-11-17 02:55:00
  • Python实现邮件的批量发送的示例代码

    2023-08-09 07:47:57
  • 教你pycharm运行Django第一个项目

    2021-08-25 16:40:07
  • delete from online where datediff

    2009-06-07 18:46:00
  • python实现在线翻译

    2021-04-02 06:06:17
  • python生成器的使用方法

    2021-12-03 22:40:49
  • 解决oracle用户连接失败的解决方法

    2011-01-04 19:35:00
  • Mysql Explain 详解

    2010-12-03 16:09:00
  • 谈谈网页一屏有多大?

    2007-12-21 12:28:00
  • 中国,美国,英国3国时间同步动态显示js代码

    2007-09-27 20:34:00
  • 详解Python连接oracle的问题记录与解决

    2021-04-07 09:38:41
  • python判定文件目录是否存在及创建多层目录

    2022-08-12 09:39:03
  • 一直闪烁变色的超级链接代码

    2008-02-27 13:08:00
  • Python学习笔记之Break和Continue用法分析

    2023-02-12 04:55:32
  • php中正则替换函数ereg_replace用法实例

    2023-06-13 03:03:51
  • 群组功能和用户沟通

    2009-07-19 14:07:00
  • Python如何通过变量ID得到变量的值

    2023-01-22 22:35:56
  • ASP网站远程客户实现EXCEL打印功能

    2009-02-02 09:01:00
  • asp之家 网络编程 m.aspxhome.com