喜欢 https://stackoverflow.com/questions/1521646/best-profanity-filter ,但对于 Python — 我正在寻找可以在本地运行和控制自己的库,而不是 Web 服务。
(虽然很高兴听到您对脏话过滤原则的基本反对意见,但我并不是专门在这里寻找它们。我知道脏话过滤无法识别出所有伤害性的话。我知道发誓,在宏伟的计划,不是一个特别大的问题。我知道您需要一些人工输入来处理内容问题。我只想找到一个好的库,看看我能用它做什么。)
最佳答案
我没有找到任何 Python 亵渎库,所以我自己做了一个。
参数
过滤器列表
匹配禁用词的正则表达式列表。请不要使用\b
,会根据inside_words
插入。
示例:
['bad', 'un\w+']
ignore_case
默认值:真
不言自明。
替换
默认值:"$@%-?!"
一个字符串,其中包含将随机生成替换字符串的字符。
示例:"%&$?!"
或 "-"
等
完成
默认值:真
控制是否替换整个字符串或是否保留第一个和最后一个字符。
inside_words
默认值:假
控制是否也在其他单词中搜索单词。禁用此功能
模块源
(最后的例子)
"""
Module that provides a class that filters profanities
"""
__author__ = "leoluk"
__version__ = '0.0.1'
import random
import re
class ProfanitiesFilter(object):
def __init__(self, filterlist, ignore_case=True, replacements="$@%-?!",
complete=True, inside_words=False):
"""
Inits the profanity filter.
filterlist -- a list of regular expressions that
matches words that are forbidden
ignore_case -- ignore capitalization
replacements -- string with characters to replace the forbidden word
complete -- completely remove the word or keep the first and last char?
inside_words -- search inside other words?
"""
self.badwords = filterlist
self.ignore_case = ignore_case
self.replacements = replacements
self.complete = complete
self.inside_words = inside_words
def _make_clean_word(self, length):
"""
Generates a random replacement string of a given length
using the chars in self.replacements.
"""
return ''.join([random.choice(self.replacements) for i in
range(length)])
def __replacer(self, match):
value = match.group()
if self.complete:
return self._make_clean_word(len(value))
else:
return value[0]+self._make_clean_word(len(value)-2)+value[-1]
def clean(self, text):
"""Cleans a string from profanity."""
regexp_insidewords = {
True: r'(%s)',
False: r'\b(%s)\b',
}
regexp = (regexp_insidewords[self.inside_words] %
'|'.join(self.badwords))
r = re.compile(regexp, re.IGNORECASE if self.ignore_case else 0)
return r.sub(self.__replacer, text)
if __name__ == '__main__':
f = ProfanitiesFilter(['bad', 'un\w+'], replacements="-")
example = "I am doing bad ungood badlike things."
print f.clean(example)
# Returns "I am doing --- ------ badlike things."
f.inside_words = True
print f.clean(example)
# Returns "I am doing --- ------ ---like things."
f.complete = False
print f.clean(example)
# Returns "I am doing b-d u----d b-dlike things."
关于python - 什么是好的 Python 亵渎过滤器库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3531746/