Search code examples
pythonfileuniquealphabetical

python find unique and put it alphabetical order


I need to find into a text file and print out both the UNIQUE words AND put in alphabetical order i know how read a file and get alphabetical but Im running into an issue with the sort and unique(I honestly don't how to do this one)

Also another problem i have is that while it gives me the words in alphabetical order is gives me "\n" each time it finds a word

TEXTFILE: mike, sara sara adam william

A= open('Wordfile.txt')
line=sorted(A.readlines())

while len(line)!=0:
print(line, end =' ')
line=A.readline()


A.close();

output: Adam, mike \n, sara \n, sara\n, william\n


Solution

  • We can do:

    A = open('Wordfile.txt')
    lines = sorted(list(set([line.rstrip() for line in A])))    # Used rstip() to remove '\n' and set() to make items unique.
    
    for line in lines:
        print(line, end =' ')
    
    A.close()