jeudi 26 mars 2015

Python filtering and sorting through a list

I just can't seem to get this to work. I need to to open file ranger.txt. Read each line, then split each line into a list of words. Check to see if each word is already in the list. If the word is not in the list, then add it to the list. At end of program, sort and print the resulting words in alphabetical order.


The result should be: ["a" "and" "buckle", "C130", "countrollin", "door", "down", "four", "Gonna", "Jump", "little", "out", "ranger", "Recon", "right", "Shuffle", "Standstrip", "the", "the", "to", "to", "take", "trip", "up", "up"]


I can get the individual lists to print, and even one word from each list, but that's it.



rangerHandle = open("ranger.txt")
count = 0
rangerList = list()

for line in rangerHandle:
line = line.rstrip()
#print line works at this point
words = line.split() # split breaks string makes another list
#print words works at this point
if words[count] not in words:
rangerList.append(words[count])
count += 1
print rangerList


ranger.txt file is:



C130 rollin down the strip
Recon ranger
Gonna take a little trip
Stand up, buckle up,
Shuffle to the door
Jump right out and count to four


And if you're going to neg vote, please at least give an explanation.


Aucun commentaire:

Enregistrer un commentaire