(审查分配器)codecadamey challenge

2024-04-29 10:39:29 发布

您现在位置:Python中文网/ 问答频道 /正文

问题描述如下: 写一个函数,可以在“否定词”出现两次后,从“否定词”列表中删除任何出现的词,也可以从上一步的列表中删除所有内容,并使用它来删除我的\u str

例如,如果您的函数具有以下文本: “我担心这个项目是可怕的,可怕的,和破碎的”。你知道吗

它应该返回: “我担心这个项目是可怕的,XXXXX,和XXXXXX”。你知道吗

这是我的密码:

negative_words = ["concerned", "behind", "danger", "dangerous", "alarming", "alarmed", "out of control", "help", "unhappy", "bad", "upset", "awful", "broken", "damage", "damaging", "dismal", "distressed", "distressed", "concerning", "horrible", "horribly", "questionable"]

my_str= "I am concerned that this project is horrible, awful, and 
broken."

def censor_three(email):`
  count = 0
  for word in negative_words:
    if word in email:
      count += 1
      if count > 2:
        email= email.replace(word, 'x'* len(word))
  return email
print(censor_three(my_str))

我得到的结果是: 我担心这个项目是xxxxxxxx,糟糕,和xxxxxx。你知道吗

我错过了什么??你知道吗


Tags: 项目函数列表emailmycountwordwords
1条回答
网友
1楼 · 发布于 2024-04-29 10:39:29

您看到这种行为的原因是循环按顺序遍历否定词列表,而不是文本中的词。列表中包含的否定词的顺序是“关注”>;“可怕”>;“破碎”>;“可怕”;这就是为什么“破碎”和“可怕”(在文本中找到的列表中的第3个和第4个词)会被审查,而“关注”和“可怕”(第1个和第2个词)则不会。你知道吗

下面是一个迭代文本的版本:

# We'll use this package to do regex replace on the text
import re

negative_words = ["concerned", "behind", "danger", "dangerous", "alarming", "alarmed", "out of control", "help", "unhappy", "bad", "upset", "awful", "broken", "damage", "damaging", "dismal", "distressed", "distressed", "concerning", "horrible", "horribly", "questionable"]

my_str = "I am concerned that this project is horrible, awful, and broken."

def censor_three(email):
  count = 0
  # Iterate over words in the text.
  # re.sub removes punctuation; str.split splits on space to produce a list of words
  for word in str.split(re.sub(r"[^A-Za-z ]", "", my_str)):
    # Now check if the word from the text is in our list of negative words
    if word in negative_words:
      count += 1
      if count > 2:
        email= email.replace(word, 'x'* len(word))
  return email
print(censor_three(my_str))

相关问题 更多 >