It's the first time I am working with Python for a Uni assignment and I am facing a difficulty regarding a task that says: Extract five longest words in the entire text, create a List with those items and order them alphabetically. Print out these results on the screen (e.g., ‘Five longest words in this text ordered alphabetically are: “word1”, “word2”, “word3”, “word4”, “word5”’)
So, the code I created so far is:
print(longest_string)
second_longest_string = sorted(word_list, key=len)[-2]
print(second_longest_string)
third_longest_string = sorted(word_list, key=len)[-3]
print(third_longest_string)
fourth_longest_string = sorted(word_list, key=len)[-4]
print(fourth_longest_string)
fifth_longest_string = sorted(list_1, key=len)[-5]
print(fifth_longest_string) ```
I thought I could start by this and then proceed to the alphabetical order, but it looks like this code generates a different output every time, because inside the list there are many strings that have the same number of words.
Any idea how I can proceed?
Thank you.
CodePudding user response:
This will sort the word list based on length and then get 5 most lengthy words and then sort them based on alphabatical order
sorted_words = sorted(sorted(word_list, key=len)[-5:])
CodePudding user response:
One of the approaches:
data = """
It's the first time I am working with Python for a Uni assignment and am facing a difficulty regarding a task that says: Extract five longest words in the entire text, create a List with those items and order them alphabetically. Print out these results on the screen"""
import re
# Remove all characters except words, space and ' from data
data = re.sub("[^a-zA-Z '] ", "", data)
words = sorted(data.split(), key=len)
print (f'Five longest words in this text ordered alphabetically are: {",".join(sorted(words[-5:]))}')
Output:
Five longest words in this text ordered alphabetically are: alphabetically,assignment,difficulty,regarding,results
CodePudding user response:
import string
Text = """It's the first time I am, working with Python for a Uni assignment and I am facing a difficulty regarding a task that says: Extract five longest words in the entire text, create a List with those items and order them alphabetically."""
EditText = ''.join([x for x in Text if x in string.ascii_letters '\'- ']) #get only words from string Text
Words = EditText.split(" ") # make a list with all worlds
SortedWords = sorted(sorted(Words, key=len)[-5:])
print(f'Five longest words in this text ordered alphabetically are: {", ".join(SortedWords)}.')
Output:
Five longest words in this text ordered alphabetically are: alphabetically, assignment, difficulty, longest, regarding.