首页 > 解决方案 > 我在这段代码中遗漏了什么,它看起来不错并且格式正确吗?

问题描述

编写一个输入文本文件的程序。程序应按字母顺序打印文件中的唯一单词。大写单词应优先于小写单词。例如,“Z”出现在“a”之前。

输入文件可以包含一个或多个句子,或者是多行单词列表。

“敏捷的棕色狐狸跳过了懒狗”

textFileName = input("Enter the input file name: ")
textFile = open(textFileName, 'r')
listOfWords = []   
while True:
        line = textFile.readline()
        if line == "":
            break
        else:
            words = line.split()
            for word in words:
                listOfWords.append(word)
                listOfWords.sort()
                uniqueListOfWords = []
                for count in range(len(listOfWords) -1):
                    if listOfWords[count]!= listOfWords[count + 1]:
                        uniqueListOfWords.append(listOfWords[count])
                        uniqueListOfWords.append(listOfWords[len(listOfWords) -1])
                        print(word)

标签: inputuppercase

解决方案


我希望我像你提到的那样进行了编辑,但是在对我的代码进行了一些更改后,这对我有用。

def sorted_unique_file(input_filename): 

    input_file = open(input_filename, 'r') #open file in read mode

    file_contents = input_file.read() #read text from file

    input_file.close()
    
    unique = []

    word_list = file_contents.split()

    for word in word_list:

        if word not in unique:

            unique.append(word) #add unique words into list

    print("unique words in alphabetical order are: ")

    print("\n".join(sorted(list(set(unique))))) #sort the words using set operation

def main():

    filename = input("Enter the input file name: ") #read the file name

    sorted_unique_file(filename) #call the function to print unique words in alphabetical order

if __name__ == "__main__":

    main()

推荐阅读