【发布时间】:2020-03-14 03:28:55
【问题描述】:
对于一个练习,我必须创建一个简单的脏话过滤器来了解课程。
过滤器使用一系列攻击性关键字和替换模板进行初始化。任何这些单词的每次出现都应替换为从模板生成的字符串。如果字长比模板短,则应使用从头开始的子字符串,对于较长的字号,应根据需要多次重复模板。
以下是我到目前为止的结果,并带有一个示例。
class ProfanityFilter:
def __init__(self, keywords, template):
self.__keywords = sorted(keywords, key=len, reverse=True)
self.__template = template
def filter(self, msg):
def __replace_letters__(old_word, replace_str):
replaced_word = ""
old_index = 0
replace_index = 0
while old_index <= len(old_word):
if replace_index == len(replace_str):
replace_index = 0
else:
replaced_word += replace_str[replace_index]
replace_index += 1
old_index += 1
return replaced_word
for keyword in self.__keywords:
idx = 0
while idx < len(msg):
index_l = msg.lower().find(keyword.lower(), idx)
if index_l == -1:
break
msg = msg[:index_l] + __replace_letters__(keyword, self.__template) + msg[index_l + len(keyword):]
idx = index_l + len(keyword)
return msg
f = ProfanityFilter(["duck", "shot", "batch", "mastard"], "?#$")
offensive_msg = "this mastard shot my duck"
clean_msg = f.filter(offensive_msg)
print(clean_msg) # should be: "this ?#$?#$? ?#$? my ?#$?"
示例应打印:
this ?#$?#$? ?#$? my ?#$?
但它会打印:
this ?#$?#$ ?#$? my ?#$?
由于某种原因,它用 6 个符号而不是 7 个(每个字母一个)替换了“mastard”一词。它适用于其他关键字,为什么不适用于这个?
此外,如果您发现其他任何问题,请随时告诉我。请记住,我是初学者,我的“工具箱”非常小。
【问题讨论】:
标签: python string class replace