Home > front end >  How to check if certain strings are in a list and replace those strings with another string in Pytho
How to check if certain strings are in a list and replace those strings with another string in Pytho

Time:01-28

I have a question for my school assignment which I'm hoping you can give me direction. Here are the requirements:

  • The goal is to have a user input a sentence
  • Then the setence is being checked for certain words "dren", "frak"
  • If those words found, then replace with "BEEP"
  • Then display the sentence with the words replaced.
  • If there aren't specific words mentioned, display the sentence the way it's entered.
  • Keep asking the question until user enters nothing.
  • You can assume the user will enter NO punctuation.

Here's the output example:

What shall I censor: Frak I messed this dren up
BEEP I messed this BEEP up

What shall I censor: Narf isn't a bad word is it
BEEP isn't a bad word is it

What shall I censor: What about zark is ZARK okay
What about BEEP is BEEP okay

What shall I censor:
Goodbye!

Here are my codes and I think I am stuck on the loop to check certain words and replace those words with "BEEP"


while True:
    # Asking for User Input
    userInput = input("What shall I censor: ").lower().strip()
    if userInput == "":
        break
    else:
        # convert string into a list
        userInputList = userInput.split(" ")

        # count how many items in the list
        userInputLength = len(userInputList)

        # Checking the bad words
        badWords = ["dren", "frak"]
        if userInputList in badWords:
            i = 0
            while i < userInputLength:
                if userInputList[i] == "dren":
                    userInputList[i] = "BEEP"
                elif userInputList[i] == "frak":
                    userInputList[i] = "BEEP"
                    i  = 1

            print(userInputList)

        else:
            print(userInputList)

CodePudding user response:

If you're familiar with regular expressions, you can replace all occurrences of all badWords in a single statement.

  • (?i) can be used to make the expression case-insensitive
  • \b can be used to mark word boundaries, if you only want to match whole words
  • (xxx|yyy) can be used to match xxx or yyy

=> r"(?i)\b(dren|frak)\b" matches WORDs dren or frak

  • "|".join(badWords) makes a string of all bad words separated by |

=> r"(?i)\b(%s)\b" % "|".join(badWords) matches WORDs that are in badWords

import re

while True:
    # Asking for User Input
    userInput = input("What shall I censor: ")

    if userInput == "":
        break

    userInput = re.sub(
        r"(?i)\b(%s)\b" % '|'.join(badWords), 
        "BEEP", 
        userInput
    )

    print(userInput)


print("Goodbye!")

Demo: https://trinket.io/python3/b9e74a81d0

CodePudding user response:

I know code only answers are frowned upon, but I though in-code narration was appropriate here:

##----------------------
# Checking the bad words
# no need to reset every time we loop.
# cast to set() to make lookups nicer.
##----------------------
badWords = ["dren", "frak"]
badWords = set(badWords)
##----------------------

while True:
    ##----------------------
    # Asking for User Input:
    # let's not alter what the user gave us so we can preserve case
    # userInput = input("What shall I censor: ").lower().strip()
    ##----------------------
    userInput = input("What shall I censor: ")    
    ##----------------------

    if userInput == "":
        break

    ##----------------------
    ## break above exits the while loop so following else is redundant
    ## remaining code tabbed out one level as a result
    ##----------------------
    # else:
    ##----------------------

    # convert string into a list
    userInputList = userInput.split(" ")

    ##----------------------
    # count how many items in the list
    # we don't need this at all
    ##----------------------
    # userInputLength = len(userInputList)
    ##----------------------

    ##----------------------
    ## rather than attempting to see if our list of works is in the list of bad words
    ## as that is not really how "in" here. lets test each word in our input at a time
    ##----------------------
    # if userInputList in badWords:
    #    i = 0
    #    while i < userInputLength:
    #        if userInputList[i] == "dren":
    #            userInputList[i] = "BEEP"
    #        elif userInputList[i] == "frak":
    #            userInputList[i] = "BEEP"
    #            i  = 1
    for i in range(len(userInputList)):
        if userInputList[i].lower() in badWords:
            userInputList[i] = "BEEP"
    ##----------------------

    ##----------------------
    ## now print the results after reassembly of the text
    ##----------------------
    print(" ".join(userInputList))
    ##----------------------

This could be simplified if you wanted to something more like:

bad_words = set([
    "dren",
    "frak",
])

while True:
    userInput = input("What shall I censor: ")
    
    if userInput == "":
        break

    censored = " ".join(
        "BEEP" if word.lower() in bad_words else word
        for word
        in userInput.split(" ")
    )

    print(censored)
  • Related