我正在进行一门在线Python课程,并陷入了这项练习(对不起,auto-translate,我的英语不好):

考虑在e-mail中检查垃圾邮件的任务或在消息中过滤禁止的单词。

is_spam_words函数接受字符串(参数text),检查列表中禁止单词的内容(参数spam_words),然后返回检查的结果:True,如果列表中至少有一个单词,并且False,如果在文本中找不到停止单词。

text参数中的单词在任何情况下都可以是,这意味着is_spam_words函数在搜索禁止的单词时是case-independent,并且所有文本都必须小写。为简单起见,让我们假设该行中只有一个禁止单词。

为该函数提供第三个参数space_around,该函数默认为False。它将负责该功能是否会搜索单个单词。如果单词的左侧有空间符号,或者它位于文本的开头,并且单词右侧有一个空间或周期符号,则认为单词被认为是单独的。

例如,我们正在寻找文本中的单词"rain"。因此,在"rainbow"一词中,挑战和结果将如下:

print(is_spam_words("rainbow", ["rain"])) # True
print(is_spam_words("rainbow", ["rain"], True)) # False

也就是说,在第二种情况下,单词不是分开的,也是另一个单词的一部分。

在此示例中,该函数将在两种情况下返回True

print(is_spam_words("rain outside.", ["rain"])) # True
print(is_spam_words("rain outside.", ["rain"], True)) # True

我的代码是:

def is_spam_words(text, spam_words, space_around=False):
    if space_around:
        text = text.lower()
        for char in spam_words:
            char.lower()
        if text.find(spam_words) != -1 or text.startswith(spam_words):
            return True
        else:
            return False
    return False

问题是:

The function returned an incorrect result for two parameters: False. Must be

is_spam_words('rain outside.', ['rain']) == True

我尝试更改主循环(例如示例1:if spam_words in text is True或example2:if (" " + spam_word + " ") in (" " + text + " ")),但我仍然不明白为什么它不起作用。我期望,如果找到word/text的垃圾邮件单词,则结果将是TrueFalse,如果找不到。

分析解答
  1. 将所有内容转换为小写,以确保case-insensitivity。
  2. 如果space_around是错误的,只需检查文本中的垃圾邮件单词是否。
  3. 如果space_around为真,我们将检查单词是否在文本的开头,然后是一个空间或一个段,如果该单词在中间,则被空间或末端包围,如果该单词是在文本的末尾,并在一个空间之前。 这是基于上述方法的解决方案:
def is_spam_words(text, spam_words, space_around=False):
    # Convert the text and spam words to lowercase
    text = text.lower()
    spam_words = [word.lower() for word in spam_words]

    for word in spam_words:
        if not space_around:
            if word in text:
                return True
        else:
            if text.startswith(word + " ") or text.endswith(" " + word) or text.endswith(" " + word + "."):
                return True
            if (" " + word + " ") in text:
                return True
            if (" " + word + ".") in text:
                return True

    return False

# Testing your examples
print(is_spam_words("rainbow", ["rain"]))  # True
print(is_spam_words("rainbow", ["rain"], True))  # False
print(is_spam_words("rain outside.", ["rain"]))  # True
print(is_spam_words("rain outside.", ["rain"], True))  # True
print(is_spam_words('Moloch god is terrible.', ['shit']))  # False