Reputation: 13
I'm wanting to read a file selected by the user via input and sort out all of the words within that txt file alphabetically. The output on this specific code is only outputting all of the letters from the txt file.
OUTPUT example: A a e l n p
desired OUTPUT: ['apple', 'ein', 'pear', 'purple']
f = open(input("What file would you like to import?"))
for word in sorted(f.read().split()):
print(sorted(word))
Upvotes: 0
Views: 50
Reputation: 16747
If you do sorted(word)
then sorted
splits your word (string) into letters and sorts them, you don't need to use sorted, just use word
as your words are already sorted! Corrected code below:
f = open(input("What file would you like to import?"))
for word in sorted(f.read().split()):
print(word)
Input file:
apple purple pear ein
Output:
apple
ein
pear
purple
If you need to have a list
in output, you may use next simple code:
f = open(input("What file would you like to import?"))
print(sorted(f.read().split()))
Input file:
apple purple pear ein
Output:
['apple', 'ein', 'pear', 'purple']
Upvotes: 0
Reputation: 23119
You were really close! You just don't want to sort the word before you print it. You've already sorted the list:
f = open(input("What file would you like to import?"))
for word in sorted(f.read().split()):
print(word)
Sample file contents:
now is the time for all good
men to come to the aid of
their country
Result:
aid
all
come
country
for
good
is
men
now
of
the
the
their
time
to
to
Upvotes: 1