Warum funktioniert replace function nicht?
Verfasst: Dienstag 13. Dezember 2022, 18:53
#!/usr/bin/env python3
# The signatures of this class and its public methods are required for the automated grading to work.
# You must not change the names or the list of parameters.
# You may introduce private/protected utility methods though.
class ProfanityFilter:
def __init__(self, keywords, template):
self.keywords = keywords
self.template = template
def cleaned(self, keyword):
len_k = len(keyword)
len_t = len(self.template)
fits = len(keyword) // len(self.template)
rest = len(keyword) % len(self.template)
changed_word = self.template * fits + self.template[:rest]
return changed_word
def filter(self, msg):
msg_copy = msg
msg_list = msg.split()
for msg_word in msg_list:
for keyword in self.keywords:
if keyword in msg_word:
idx = msg_word.find(keyword)
cleaned_word = self.cleaned(keyword)
final_word = msg_word[:idx] + cleaned_word + msg_word[len(cleaned_word) + idx:]
msg_copy.replace(msg_word, final_word)
return msg_copy
# You can play around with your implementation in the body of the following 'if'.
# The contained statements will be ignored while evaluating your solution.
if __name__ == '__main__':
f = ProfanityFilter(["duck", "shot", "batch", "mastard"], "?#$")
offensive_msg = "abc defghi mastard jklmno"
clean_msg = f.filter(offensive_msg)
print(clean_msg) # abc defghi ?#$?#$? jklmno
# The signatures of this class and its public methods are required for the automated grading to work.
# You must not change the names or the list of parameters.
# You may introduce private/protected utility methods though.
class ProfanityFilter:
def __init__(self, keywords, template):
self.keywords = keywords
self.template = template
def cleaned(self, keyword):
len_k = len(keyword)
len_t = len(self.template)
fits = len(keyword) // len(self.template)
rest = len(keyword) % len(self.template)
changed_word = self.template * fits + self.template[:rest]
return changed_word
def filter(self, msg):
msg_copy = msg
msg_list = msg.split()
for msg_word in msg_list:
for keyword in self.keywords:
if keyword in msg_word:
idx = msg_word.find(keyword)
cleaned_word = self.cleaned(keyword)
final_word = msg_word[:idx] + cleaned_word + msg_word[len(cleaned_word) + idx:]
msg_copy.replace(msg_word, final_word)
return msg_copy
# You can play around with your implementation in the body of the following 'if'.
# The contained statements will be ignored while evaluating your solution.
if __name__ == '__main__':
f = ProfanityFilter(["duck", "shot", "batch", "mastard"], "?#$")
offensive_msg = "abc defghi mastard jklmno"
clean_msg = f.filter(offensive_msg)
print(clean_msg) # abc defghi ?#$?#$? jklmno