# Ask for inputs
fileName = input("Please enter the filename: ")
f = open(fileName, 'r')
lines = f.read()
f.close()
#Input the text, find unique words and add to a list
words = []
wordList = lines.split()
for word in wordList:
if word not in words:
words.append(word)
words.sort()
print("words in aphabetical order are: ")
def main():
fileName = input("Enter the input file name: ")
sorted_words_file(fileName)
if __name__ == "__main__":
main()
uj5u.com熱心網友回復:
我相信這就是你要找的。
from string import whitespace
def sorted_words_file(fileName):
# Read the text, find unique words and add to a list
f = open(fileName, 'r')
lines = f.read()
f.close()
wordList = lines.split()
# Remove surrounding whitespace and drop empty strings (if any)
wordList = [w.strip(whitespace) for w in wordList if w.strip(whitespace)]
# Get unique words and sort them
words = sorted(list(set(wordList)))
print("words in aphabetical order are:", words)
def main():
# Ask for inputs
fileName = input("Enter the input file name: ")
sorted_words_file(fileName)
if __name__ == "__main__":
main()
請注意,排序時大小寫很重要,以小寫字母開頭的單詞在大寫單詞之后。如果你不關心這個,只需將 a 放在.lower()清理串列理解行中。
uj5u.com熱心網友回復:
鑒于檔案名,整個事情是一個單行:
sorted(list(set(open(filename, "r").read().split())))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/378060.html
上一篇:附加拆分輸出的更短的解決方案
下一篇:如何連接同樣分塊的子串列串列
