欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺談Python 敏感詞過濾的實(shí)現(xiàn)

 更新時(shí)間:2019年08月15日 09:32:47   作者:xiabe  
這篇文章主要介紹了淺談Python 敏感詞過濾的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

一個(gè)簡單的實(shí)現(xiàn)

class NaiveFilter():

  '''Filter Messages from keywords

  very simple filter implementation

  >>> f = NaiveFilter()
  >>> f.add("sexy")
  >>> f.filter("hello sexy baby")
  hello **** baby
  '''

  def __init__(self):
    self.keywords = set([])

  def parse(self, path):
    for keyword in open(path):
      self.keywords.add(keyword.strip().decode('utf-8').lower())

  def filter(self, message, repl="*"):
    message = str(message).lower()
    for kw in self.keywords:
      message = message.replace(kw, repl)
    return message

其中strip() 函數(shù) 刪除附近的一些空格,解碼采用utf-8的形式,然后將其轉(zhuǎn)為小寫。

parse()函數(shù)就是打開文件,然后從中取各個(gè)關(guān)鍵詞,然后將其存在關(guān)鍵詞集合中。

filter()函數(shù)是一個(gè)過濾器函數(shù),其中將消息轉(zhuǎn)化為小寫,然后將關(guān)鍵詞替換成*。、

class BSFilter:

  '''Filter Messages from keywords

  Use Back Sorted Mapping to reduce replacement times

  >>> f = BSFilter()
  >>> f.add("sexy")
  >>> f.filter("hello sexy baby")
  hello **** baby
  '''

  def __init__(self):
    self.keywords = []
    self.kwsets = set([])
    self.bsdict = defaultdict(set)
    self.pat_en = re.compile(r'^[0-9a-zA-Z]+$') # english phrase or not

  def add(self, keyword):
    if not isinstance(keyword, str):
      keyword = keyword.decode('utf-8')
    keyword = keyword.lower()
    if keyword not in self.kwsets:
      self.keywords.append(keyword)
      self.kwsets.add(keyword)
      index = len(self.keywords) - 1
      for word in keyword.split():
        if self.pat_en.search(word):
          self.bsdict[word].add(index)
        else:
          for char in word:
            self.bsdict[char].add(index)

  def parse(self, path):
    with open(path, "r") as f:
      for keyword in f:
        self.add(keyword.strip())

  def filter(self, message, repl="*"):
    if not isinstance(message, str):
      message = message.decode('utf-8')
    message = message.lower()
    for word in message.split():
      if self.pat_en.search(word):
        for index in self.bsdict[word]:
          message = message.replace(self.keywords[index], repl)
      else:
        for char in word:
          for index in self.bsdict[char]:
            message = message.replace(self.keywords[index], repl)
    return message

在上面的實(shí)現(xiàn)例子中,對(duì)于搜索查找進(jìn)行了優(yōu)化,對(duì)于英語單詞,直接進(jìn)行了按詞索引字典查找。對(duì)于其他語言模式,我們采用逐字符查找匹配的一種模式。

BFS:寬度優(yōu)先搜索方式。

class DFAFilter():

  '''Filter Messages from keywords

  Use DFA to keep algorithm perform constantly

  >>> f = DFAFilter()
  >>> f.add("sexy")
  >>> f.filter("hello sexy baby")
  hello **** baby
  '''

  def __init__(self):
    self.keyword_chains = {}
    self.delimit = '\x00'

  def add(self, keyword):
    if not isinstance(keyword, str):
      keyword = keyword.decode('utf-8')
    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(keyword.strip())

  def filter(self, message, repl="*"):
    if not isinstance(message, str):
      message = message.decode('utf-8')
    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)

DFA即Deterministic Finite Automaton,也就是確定有窮自動(dòng)機(jī)。

使用了嵌套的字典來實(shí)現(xiàn)。

參考

Github:敏感詞過濾系統(tǒng)

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • python爬蟲 正則表達(dá)式使用技巧及爬取個(gè)人博客的實(shí)例講解

    python爬蟲 正則表達(dá)式使用技巧及爬取個(gè)人博客的實(shí)例講解

    下面小編就為大家?guī)硪黄猵ython爬蟲 正則表達(dá)式使用技巧及爬取個(gè)人博客的實(shí)例講解。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-10-10
  • Pandas 如何篩選包含特定字符的列

    Pandas 如何篩選包含特定字符的列

    這篇文章主要介紹了Pandas 如何篩選包含特定字符的列,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2021-03-03
  • 四個(gè)Python操作Excel的常用腳本分享

    四個(gè)Python操作Excel的常用腳本分享

    在數(shù)字化時(shí)代,很多人工作中經(jīng)常和excel打交道。本文和大家分享四個(gè)Python操作excel的腳本,讓你工作效率更高,需要的小伙伴可以參考一下
    2022-11-11
  • python先序遍歷二叉樹問題

    python先序遍歷二叉樹問題

    這篇文章主要介紹了python先序遍歷二叉樹問題,簡單分析了問題,然后向大家分享了代碼示例,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-11-11
  • Python使用Nocalhost并開啟debug調(diào)試的方法

    Python使用Nocalhost并開啟debug調(diào)試的方法

    Nocalhost是一種開發(fā)者工具,支持針對(duì)Kubernetes應(yīng)用程序進(jìn)行調(diào)試和部署,這篇文章主要介紹了Python怎么使用Nocalhost并開啟debug,需要的朋友可以參考下
    2023-04-04
  • 最新python正則表達(dá)式(re模塊)詳解

    最新python正則表達(dá)式(re模塊)詳解

    在Python中需要通過正則表達(dá)式對(duì)字符串進(jìn)?匹配的時(shí)候,可以使??個(gè)python自帶的模塊,名字為re,這篇文章主要介紹了python正則表達(dá)式(re模塊)詳解,需要的朋友可以參考下
    2023-01-01
  • python中有關(guān)時(shí)間日期格式轉(zhuǎn)換問題

    python中有關(guān)時(shí)間日期格式轉(zhuǎn)換問題

    這篇文章主要介紹了python中有關(guān)時(shí)間日期格式轉(zhuǎn)換問題,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-12-12
  • 使用Python破解RAR文件密碼的代碼實(shí)例

    使用Python破解RAR文件密碼的代碼實(shí)例

    這篇文章主要介紹了使用Python破解RAR文件密碼的代碼實(shí)例,rar 壓縮文件資源又不少是被加密的,密碼通常也比較簡單,我們可以通過暴力破解的方式來獲取,通常耗時(shí)也比較小,需要的朋友可以參考下
    2023-11-11
  • Python多線程模塊Threading用法示例小結(jié)

    Python多線程模塊Threading用法示例小結(jié)

    這篇文章主要介紹了Python多線程模塊Threading用法,結(jié)合實(shí)例形式分析了Python多線程模塊Threading相關(guān)概念、原理、進(jìn)程與線程的區(qū)別及使用技巧,需要的朋友可以參考下
    2019-11-11
  • python 將視頻 通過視頻幀轉(zhuǎn)換成時(shí)間實(shí)例

    python 將視頻 通過視頻幀轉(zhuǎn)換成時(shí)間實(shí)例

    這篇文章主要介紹了python 將視頻 通過視頻幀轉(zhuǎn)換成時(shí)間實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-04-04

最新評(píng)論