简体   繁体   中英

I want to redact a sentence and return # for every third word in the sentence

Write a function that will redact every third word in a sentence. Make use of the hashtag (#) symbol to redact the characters that make up the word, ie if the word is five characters long then a string of five hashtags should replace that word. However, this should not redact any of the following punctuation marks:

apostrophes (') quotations (") full stops (.) commas (,) exclamations (?) question marks (:) colons (;) semicolons (:) Arguments:

sentence (string) → sentence that needs to be redacted. Return:

redacted sentence (string) → every third word should be redacted.

This is the function, but i haven't tried anything, i'm just confused

def redact_words(sentence):
    sentence = sentence.split()
    for word in sentence[2:3]:
        for i in word:
            word.replace('i', '#')
            redacted_sentence = 
    return redacted_sentence
### END FUNCTION   

Expected output

sentence = "My dear Explorer, do you understand the nature of the given question?"
redact_words(sentence) ==  'My dear ########, do you ########## the nature ## the given ########?'

sentence = "Explorer, this is why you shouldn't come to a test unprepared."
redact_words(sentence)=="Explorer, this ## why you #######'# come to # test unprepared."

please help

def redact_words(sentence):
    # split the sentence into individual words
    words = sentence.split(" ")
    # initialize a variable to hold the redacted sentence
    redacted_sentence=""
    # Set a counter for iteration
    i=1
    for word in words:
        # This would select every third word in the sentence
        if i%3==0:
            # When the word has been selected, store it in a variable to
            # perform the redaction operation on it.
            redaction=""
            for character in word:
                # At this point, we want to separate the punctuations from
                # the  letters in the selected word
                if character in '\'".,!?;:':
                    redaction = redaction + character
                else:
                    redaction = redaction +'#'
            # Piece back together the redacted word with the sentence
            redacted_sentence = redacted_sentence+" "+redaction
        else:
            # Piece back together the word not redacted
            redacted_sentence = redacted_sentence+" "+word
        i+=1
    # Return the redacted sentence and remove the spaces.
    return redacted_sentence.strip()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM