用变量 python 切换 1 个字符串中的多个单词

switch multiple words in 1 string with variable, python

class Cleaner:
    def __init__(self, forbidden_word = "frack"):
        """ Set the forbidden word """
        self.word = forbidden_word

    def clean_line(self, line):
        """Clean up a single string, replacing the forbidden word by *beep!*"""
        found = line.find(self.word)
        if found != -1 :
            return line[:found] + "*beep!*" + line[found+len(self.word):] 
        return line

    def clean(self, text):
        for i in range(len(text)):
            text[i] = self.clean_line(text[i])


example_text = [
        "What the frack! I am not going",
        "to honour that question with a response.",
        "In fact, I think you should",
        "get the fracking frack out of here!",
        "Frack you!"
        ]

大家好,以下代码的问题是当我 运行 它时,我得到以下结果:

What the *beep!*! I am not going
to honour that question with a response.
In fact, I think you should
get the *beep!*ing frack out of here!
Frack you! 

在倒数第二行,"frack" 之一未被更改。

我试过使用 if In line 方法,但这不适用于变量。那么我如何使用 if 语句来跟踪变量而不是字符串呢?但也改变了每一个需要改变的词?

PS。它的考试练习我没有自己编写代码。

预期结果应该是:

What the *beep!*! I am not going
to honour that question with a response.
In fact, I think you should
get the *beep!*ing *beep!* out of here!
Frack you! 

这是因为 line.find(...) 只会 return 第一个结果,然后您将其替换为 "*beep!*" 然后 return,因此会丢失其他匹配项。

要么使用 find iteratively, passing in the appropriate start index each time until the start index exceeds the length of the line, or use Python's replace 方法为您完成所有这些。

我建议更换:

found = line.find(self.word)
if found != -1 :
    return line[:found] + "*beep!*" + line[found+len(self.word):]
return line

return line.replace(self.word, "*beep!*")

这将自动找到所有匹配项并进行替换。