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".