我想写一个函数,用lis中的其他值替换字符串的某些部分

2024-05-15 19:51:05 发布

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

我的目标是“审查”某些要求的电子邮件。我在第二封邮件中,需要帮助,因为我应该用删失替换列表中出现在变量中的所有字符串实例,但它只替换列表中的一个字符串。不知道该怎么办。代码学院的项目

# These are the emails you will be censoring. The open() function is opening the text file that the emails are contained in and the .read() method is allowing us to save their contexts to the following variables:
email_one = open("email_one.txt", "r").read()
email_two = open("email_two.txt", "r").read()
email_three = open("email_three.txt", "r").read()
email_four = open("email_four.txt", "r").read()

#variables, lists, and etc
proprietary_terms = ["she", "personality matrix", "sense of self", "self-preservation", "learning algorithm", "her", "herself"]
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"]

def censor(email):
    if email  == email_one:
       new_str = email_one.replace("learning algorithms", "*CENSORED*")
    return new_str
    elif email == email_two:
      for terms in proprietary_terms:
      new_str = email_two.replace(terms, "*CENSORED*")
    return new_str

#test code here
print(censor(email_two))

原始电子邮件(运行代码之前): 早上好,投资者委员会

这周有很多更新。学习算法的效果比我们想象的要好。我们最初的内部数据转储已经完成,我们已经开始计划将系统连接到互联网和哇!结果令人震惊

她学习比以往任何时候都快。她的学习速度,现在她可以访问万维网成倍增长,远远快于我们,虽然学习算法的能力

不仅如此,我们还配置了她的人格矩阵,以便系统与我们的研究团队进行交流。这就是为什么我们知道她认为自己是一个她!我们问了

有多酷?我们没料到一个人的个性会在这个过程的早期发展,但似乎一种基本的自我意识正在开始形成。这是这一进程中的一个重要步骤,因为有了自我意识和自我保护意识,她就能看到世界面临的问题,并为改善地球作出艰难但必要的决定

我们在实验室里兴奋不已,希望投资者也能分享我们的热情

直到下个月, 弗朗辛,首席科学家


代码打印出: 早上好,投资者委员会

这周有很多更新。学习算法的效果比我们想象的要好。我们最初的内部数据转储已经完成,我们已经开始计划将系统连接到互联网和哇!结果令人震惊

她学习比以往任何时候都快。她的学习速度,现在她可以访问万维网成倍增长,远远快于我们,虽然学习算法的能力

不仅如此,我们还配置了她的人格矩阵,以便系统与我们的研究团队进行交流。这就是为什么我们知道她认为被审查的是她!我们问了

有多酷?我们没料到一个人的个性会在这个过程的早期发展,但似乎一种基本的自我意识正在开始形成。这是这一进程中的一个重要步骤,因为有了自我意识和自我保护意识,她就能看到世界面临的问题,并为改善地球作出艰难但必要的决定

我们在实验室里兴奋不已,希望投资者也能分享我们的热情

直到下个月, 弗朗辛,首席科学家


Tags: the代码txt算法newread投资者电子邮件
1条回答
网友
1楼 · 发布于 2024-05-15 19:51:05

问题是,你一次又一次地更换同一件东西。当您进行另一个替换时,您正在覆盖第一个替换。典型的解决方案是首先生成一个字符串,然后不断重复修改它,如下所示:

elif email == email_two:
    new_str = email_two                                 # make new_str a persistent variable
    for terms in proprietary_terms:
        new_str = new_str.replace(terms, "*CENSORED*")  # continuously change new_str
    return new_str  

相关问题 更多 >