Question

In python, how to sort the 10 highest word length from a txt file displayed in an ascending order?

Word list:
pizza
toy
phone
computer
chair
desk
shelf
cup
bed
window
clock
house
roof
pen

example:

Enter name of files on at a time. when ready to compile, enter done: done longest words! responsibilities: 16 letters inter

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code Screenshot :

#Prompting the user for filename filename=input(Please enter the filename: ) #Opening the file with open(filename) as f: co

Executable Code:

#Prompting the user for filename
filename=input("Please enter the filename: ")

#Opening the file
with open(filename) as f:
   content = f.readlines()
#Storing the words into a list
content = [x.strip() for x in content]

#Sorting the list
lst2 = sorted(content, key=len,reverse=True)

count=0
#printing the result
for i in lst2:
   #BReaks out of loop when reached 10
   if count==10:
       break
   print(str(i)+"%-10s" %":"+str(len(i))+" letters")
   count=count+1

Sample Output:

Please Note : you can change the value of reverse above to be True or False for ascending or descending


Save the text file in the same folder as the code :

sample.txt 1 2 3 4 5 pizza toy phone computer chair desk shelf cup bed window clock house roof pen 9 10 11 12 13 14



When reverse = True

It prints in Descending :

Please enter the filename: sample.txt computer: 8 letters window: 6 letters pizza: 5 letters phone: 5 letters chair: 5 letter

When reverse=False m it prints in ascending :

Please enter the filename: sample.txt toy: 3 letters cup: 3 letters bed: 3 letters pen: 3 letters desk: 4 letters roof: 4 let

Please comment below if you have any queries or if you require any modifications.
Please do give a thumbs up if you liked my answer thanks :)


Add a comment
Know the answer?
Add Answer to:
In python, how to sort the 10 highest word length from a txt file displayed in...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT