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

yipeiwu_com5年前Python基础

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

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

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

# -*- 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设计】。

相关文章

Python urllib模块urlopen()与urlretrieve()详解

1.urlopen()方法urllib.urlopen(url[, data[, proxies]]) :创建一个表示远程url的类文件对象,然后像本地文件一样操作这个类文件对象来获取远...

对numpy和pandas中数组的合并和拆分详解

合并 numpy中 numpy中可以通过concatenate,指定参数axis=0 或者 axis=1,在纵轴和横轴上合并两个数组。 import numpy as np impo...

python3实现钉钉消息推送的方法示例

背景 偶然发现一个python实现的按照农历/阴历推送消息提醒的程序,钉钉群消息推送。此处总结并对其可推送的消息做。 DingtalkNotice 环境:python3.7 安装:...

基于Python解密仿射密码

基于Python解密仿射密码

新学期有一门密码学课,课上老师布置了一道密码学题,题目如下: 解密由仿射密码加密的密文“DBUHU SPANO SMPUS STMIU SBAKN OSMPU SS” 想解密这个密文,首...

使用Matplotlib 绘制精美的数学图形例子

使用Matplotlib 绘制精美的数学图形例子

一个最最简单的例子: 绘制一个从 0 到 360 度完整的 SIN 函数图形 import numpy as np import matplotlib.pyplot as pt...