這是我第一次使用 Python 進行 Uni 作業,并且我在執行以下任務時遇到了困難:
提取整個文本中最長的五個單詞,用這些專案創建一個串列并按字母順序排列。在螢屏上列印出這些結果(例如,'本文中按字母順序排列的五個最長單詞是:“word1”、“word2”、“word3”、“word4”、“word5”')
所以,到目前為止我創建的代碼是:
longest_string = sorted(word_list, key=len)
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) ```
我以為我可以從這個開始,然后按字母順序進行,但看起來這段代碼每次都會生成不同的輸出,因為在串列中有許多具有相同單詞數的字串。
知道我該如何繼續嗎?
uj5u.com熱心網友回復:
這將根據長度對單詞串列進行排序,然后獲得 5 個最長的單詞,然后根據字母順序對它們進行排序
sorted_words = sorted(sorted(word_list, key=len)[-5:])
uj5u.com熱心網友回復:
方法之一:
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:]))}')
輸出:
Five longest words in this text ordered alphabetically are: alphabetically,assignment,difficulty,regarding,results
uj5u.com熱心網友回復:
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)}.')
輸出:
Five longest words in this text ordered alphabetically are: alphabetically, assignment, difficulty, longest, regarding.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/370911.html
上一篇:洗掉資料框中“\”之后的字符
