SirClink
SirClink

Reputation: 13

Why am I not getting words, only letters?

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.

f = open(input("What file would you like to import?"))
for word in sorted(f.read().split()):
    print(sorted(word))

Upvotes: 0

Views: 50

Answers (2)

Arty
Arty

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:

Try it online!

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:

Try it online!

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

CryptoFool
CryptoFool

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

Related Questions