如何使用Python查詢文字檔案中最短的單詞?
在本文中,我們將向您展示如何使用Python列印給定文字檔案中所有最短的單詞。最短的單詞是指長度與文字檔案中最短單詞(最小長度)相同的單詞。
假設我們有一個名為TextFile.txt的文字檔案,其中包含一些隨機文字。我們將返回給定文字檔案中所有最短的單詞。
TextFile.txt
Good Morning Tutorials Point This is the Tutorials Point sample File Consisting of Specific abbreviated source codes in Python Seaborn Scala Imagination Summary and Explanation Welcome user Learn with joy
演算法(步驟)
以下是執行所需任務的演算法/步驟:
建立一個變數來儲存文字檔案的路徑。
使用open()函式(開啟檔案並返回檔案物件作為結果)以只讀模式開啟文字檔案,將檔名和模式作為引數傳遞給它(此處“r”表示只讀模式)。
with open(inputFile, 'r') as filedata:
建立一個變數,使用read()函式(讀取檔案中指定數量的位元組並返回它們。預設值為-1,這意味著整個檔案)讀取文字檔案資料,並使用split()函式(將字串拆分為列表。我們可以定義分隔符;預設分隔符是任何空格)將其拆分為給定文字檔案的單詞列表。
使用len()(len()方法返回物件中的專案數。當物件是字串時,它返回字串中的字元數)和min()(返回可迭代物件中最小值的專案)函式從上面的單詞列表中查詢最短單詞的長度。
len(min(words List, key=len))
使用列表推導式,獲取所有具有最短長度的單詞並將它們儲存在另一個變數中。在這裡,我們遍歷檔案的每個單詞,並使用列表推導式中的for迴圈檢查該單詞的長度是否等於最短單詞的長度。
key=len指定我們必須根據單詞的長度獲取單詞,我們將使用min()函式獲取最小長度的單詞,並使用len()函式獲取最小長度單詞的長度。
list comprehension:
列印給定文字檔案中所有最短的單詞。
使用close()函式(用於關閉已開啟的檔案)關閉輸入檔案。
當您希望根據現有列表的值構建新列表時,列表推導式提供了一種更短/簡潔的語法。
示例
以下程式檢查最短單詞的長度,並列印所有長度與給定文字檔案中最短單詞長度相同的單詞:
# input text file inputFile = "ExampleTextFile.txt" # Opening the given file in read-only mode. with open(inputFile, 'r') as filedata: # Getting the list of words from a file wordsList = filedata.read().split() # finding the length of the shortest word in the above words list shortestWordLength = len(min(wordsList, key=len)) # Storing all the words having the minimum length(shortest word length) result = [textword for textword in wordsList if len(textword) == shortestWordLength] # Print the shortest words from a text file print("The following are the shortest words from a text file:") print(result) # Closing the input file filedata.close()
輸出
執行上述程式將生成以下輸出:
The following are the shortest words from a text file: ['is', 'of', 'in']
在這個程式中,我們從文字檔案中讀取一些隨機文字。我們讀取整個檔案並將其分解成單詞。獲得單詞後,我們確定了最小長度單詞的長度。然後,我們逐字遍歷檔案,檢查相應單詞的長度是否等於最小長度單詞的長度。如果為真,我們將列印這些單詞並關閉開啟的檔案。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP