我从CS50的pset 6中为bleep.py编写了一些代码,但未获得预期的输出,并且在程序中似乎找不到任何错误

时间:2019-10-08 19:23:16

标签: python string cs50

CS50 Pset 6 bleep.py代码未返回预期输出

我尝试在几乎所有地方打印变量的值。

程序中不打印的部分位于条件为BWord == TWord的IF分支中

(即使BWord和TWord相同,程序也永远不会进入此分支)。

    from cs50 import get_string
        from sys import argv


        def main():
            if len(argv) != 2:
                print("Usage: python bleep.py <filename>")
                exit(1)
            text = get_string("Enter your text here: ")
            filename = argv[1]
            fileheader = open(filename, "r")
            Word = fileheader.readline()
            BannedWords = []
            while Word != "":
                BannedWords.append(Word)
                Word = fileheader.readline()
            fileheader.close()
            TWords = text.split()
            OutString = ""
            for TWord in TWords:
                WFound = False
                NewWord = ""
                for BWord in BannedWords:
                    if BWord == TWord:
                        WFound = True
                        length = len(TWord)
                        for number in range(length):
                            NewWord = NewWord + "*"
                        break
                if WFound == False:
                    NewWord = TWord
                if OutString == "":
                    OutString = OutString + NewWord
                else:
                    OutString = OutString + " " + NewWord
            OutString = OutString + "\n"
            print(OutString)

        if __name__ == "__main__":
            main()

使用课程提供的banned.txt,当输入“ darn it”时,我应该得到“ **** it”的输出,但实际上是“ darn it”。

0 个答案:

没有答案