如何使用 Python 查詢文字檔案中的最長單詞?
在本文中,我們將向您展示如何使用 Python 從給定的文字檔案中列印所有最長的單詞。最長的單詞是指與文字檔案中最長單詞(最大長度)具有相同長度的單詞。
假設我們獲取了一個名為 ExampleTextFile.txt 的文字檔案,其中包含一些隨機文字。我們將返回給定文字檔案中的所有最長單詞。
ExampleTextFile.txt
Good Morning Tutorials Point This is Tutorials Point sample File Consisting of Specific abbreviated source codes in Python Seaborn Scala Imagination Summary and Explanation Welcome user Learn with a joy
演算法(步驟)
以下是執行所需任務的演算法/步驟:
建立一個變數來儲存文字檔案的路徑。
使用 open() 函式(開啟檔案並返回檔案物件作為結果)以只讀模式開啟文字檔案,並將檔名和模式作為引數傳遞給它(此處“r”表示只讀模式)。
with open(inputFile, 'r') as filedata:
建立一個變數,使用 read() 函式(讀取檔案中的指定位元組數並返回它們。預設值為 -1,表示整個檔案)讀取文字檔案資料,並使用 split() 函式(將字串拆分為列表。我們可以定義分隔符;預設分隔符是任何空格)將其拆分為給定文字檔案的單詞列表。
使用 len()(len() 方法返回物件中的專案數。當物件是字串時,它返回字串中的字元數)和 max()(返回最高值專案,或可迭代物件中的最高值專案)函式從上述單詞列表中查詢最長單詞的長度。
len(max(words List, key=len))
key=len 指定我們必須根據單詞的長度獲取單詞,我們將使用 max() 函式獲取最大長度單詞,並使用 len() 函式獲取最大長度單詞的長度。
使用 列表推導式,獲取所有具有最長長度的單詞並將它們儲存在另一個變數中。在這裡,我們遍歷檔案中的每個單詞,並使用列表推導式中的 for 迴圈檢查該單詞的長度是否等於最長單詞的長度。
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 of a file wordsList = filedata.read().split() # finding the length of the longest word in the above words list longestWordLength = len(max(wordsList, key=len)) # Storing all the words having the maximum length(longest word length) # Here, we are checking all the words whose length is equal to that of the longest word result = [textword for textword in wordsList if len(textword) == longestWordLength] # Print the longest words from a text file print("The following are the longest words from a text file:") print(result) # Closing the input file filedata.close()
輸出
執行上述程式將生成以下輸出:
The following are the longest words from a text file: ['abbreviated', 'Imagination', 'Explanation']
在這個程式中,我們從文字檔案讀取了一些隨機文字。我們讀取了整個檔案並將檔案分解成單詞。在獲取單詞後,我們確定了最大長度單詞的長度。然後,我們逐個單詞遍歷檔案,檢查相應單詞的長度是否等於最小長度單詞的長度。如果是,我們將列印這些單詞並關閉開啟的檔案。
結論
因此,從本文中,我們學習瞭如何一次讀取整個檔案內容,這對於在整個文件中搜索任何單詞而不是逐行搜尋很有用。我們還學習瞭如何使用 split() 函式將檔案內容拆分為單詞,以及如何確定最短單詞的長度。在確定最大長度後,我們學習瞭如何掃描整個檔案內容以查詢最大長度單詞。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP