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:
Code Screenshot :
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 :
When reverse = True
It prints in Descending :
When reverse=False m it prints in ascending
:
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
:)
In python, how to sort the 10 highest word length from a txt file displayed in...