Search code examples
pythonsortingascii

Need to have the full word come back instead of just the first letter


##Write a program that inputs a text file. 
##The program should print the unique words in the file in alphabetical order. 
##Uppercase words should take precedence over lowercase words. For example, 'Z' comes before 'a'.
## The quick brown fox jumps over the lazy dog

    file_words = open("Words.txt", 'r+')
    words_list = []
    first_val_list = []

    for line in file_words:
        for word in line.split():
            words_list.append(word)

    for word in words_list:
        first_val = word[0]
        ascii = ord(first_val)
        first_val_list.append(first_val)

    first_val_list.sort(reverse=False)

Now this outputs ['T', 'b', 'd', 'f', 'j', 'l', 'o', 'q', 't'], which is what I need it to do but with the entire word. For Example, ['The', 'brown', 'dog', 'fox', 'jumps', 'lazy', 'over', 'quick', 'the']

The print of the first_val_list was just to see if what I had so far was working. So how would I get the full word back onto the first letter I'm new to programming in general and have around 10 weeks experience so explain like I'm 5 please.


Solution

  • first_val is the first letter of the word. So you're only putting the first letter into the list, rather than the whole word.

    You're also not removing duplicates. You can do this by converting the list of words to a set.

    with open("words.txt") as file_words:
        words_list = file_words.read().split()
    
    unique_words = set(words_list)
    sorted_words = sorted(unique_words)