Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I'm trying a homework assignment wherein I should censor some words from a sentence. There is a list of words to be censored and the program should censor those words in the sentence it gets from user input.

I have already solved the problem, but along the way I tried something that I also expected to work, but it didn't. Below are the two different programs, one of which works and the other that doesn't. The only difference is in the line where the word_list[i] gets searched in fin.

from cs50 import get_string

from sys import argv

def main():

if len(argv) != 2:

        print("Usage: python bleep.py dictionary")

        exit(1)

    fin = open(argv[1])

    print("What message would you like to censor?")

    message = get_string()

    word_list = message.split()

    # This variant works.

    for i in range(len(word_list)):

        if (word_list[i].lower() + '\n') in fin:

            word_list[i] = '*' * len(word_list[i])

        fin.seek(0)

    # The following doesn't work.

    # for i in range(len(word_list)):

    #    if word_list[i].lower() in fin.read(): 

    #        word_list[i] = '*' * len(word_list[i])

    #    fin.seek(0)

    print(' '.join(word_list))

    fin.close()

if __name__ == "__main__":

    main()

Let's say I wanted to censor "heck" with ****, but the second program also censors a string like "he" which is only a part of "heck".

1 Answer

0 votes
by (25.1k points)

The issue with the code is that the work “heck” starts with “he” i.e. it contains he. You can get around it by checking if the word ends with a new line character i.e. ‘\n’. Also instead of read each word from file one by one you can just read the entire file in memory as a string or if the file is huge then read file contents in a buffer of a fixed size.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...