我已正确编写并执行了代码,但结果与预期的略有不同。
例如,如果输入“ gosh darn it”,则应返回“ **** **** it”
但是我无法弄清楚如何在创建列表时保留用户输入的空白,因此我只打印出列表中每个单词的空格。
有人可以告诉我正确的方法吗?非常感谢。
from cs50 import get_string
from sys import argv
words = set()
def main():
#check command-line argument
if len(argv) != 2:
print("Usage: python bleep.py dictionary")
exit(1)
#load txt file
load(argv[1])
#prompt user input
user_in = get_string("What message would you like to censor?")
#tokenize input
tokens = user_in.split()
#check with txt
for i in tokens:
if check(i):
for j in i:
print("*", end="")
else:
print(i, end="")
print(" ", end="")
return True
def load(banned):
#load word in txt file
file = open(banned, "r")
for line in file:
words.add(line.rstrip("\n"))
file.close()
return True
def check(word):
#Return true if word is in dictionary else false
return word.lower() in words
if __name__ == "__main__":
main()