How do I convert a text file into a list while deleting duplicate words and sorting the list in Python? -


i'm trying read lines in file, split lines words, , add individual words list if not in list. lastly, words have sorted. i've been trying right while, , understand concepts, i'm not sure how exact language , placement right. here's have:

filename = raw_input("enter file name: ") openedfile = open(filename) lst = list() line in openedfile:     line.rstrip()     words = line.split() word in words:     if word not in lst:         lst.append(words) print lst 

if you're splitting text file words based on whitespace, use split() on whole thing. there's nothing gained reading each line , stripping it, because split() handles that.

so initial list of words, need this:

filename = raw_input("enter file name: ") openedfile = open(filename) wordlist = openedfile.read().split() 

then remove duplicates, convert word list set:

wordset = set(wordlist) 

and sort it:

words = sorted(wordset) 

this can simplified 3 lines, so:

filename = raw_input("enter file name: ") open(filename) stream:     words = sorted(set(stream.read().split())) 

(nb: with statement automatically close file you)


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -