如何使用 Python 查詢文字檔案中給定單詞的行號?
在本文中,我們將向您展示如何使用 Python 獲取文字檔案中給定單詞所在的行號。
假設我們有一個名為 **TextFile.txt** 的文字檔案,其中包含一些隨機文字。我們將返回文字檔案中給定單詞所在的行號。
TextFile.txt
Good Morning TutorialsPoint This is TutorialsPoint sample File Consisting of Specific source codes in Python,Seaborn,Scala Summary and Explanation Welcome TutorialsPoint Learn with a joy
演算法(步驟)
以下是執行所需任務的演算法/步驟:
建立一個變數來儲存文字檔案的路徑。
建立一個變數(儲存行號)並將其值初始化為 1。
輸入單詞作為靜態/動態輸入,並將其儲存在一個變數中。
使用 **open()** 函式(開啟檔案並返回檔案物件作為結果)以只讀模式開啟文字檔案,並將檔名和模式作為引數傳遞給它(此處“r”表示只讀模式)。
with open(inputFile, 'r') as fileData:
使用 for 迴圈遍歷文字檔案的每一行。
使用 **split()** 函式(將字串拆分為列表。我們可以定義分隔符;預設分隔符是任何空格)將文字檔案的每一行拆分為單詞列表,並將其儲存在一個變數中。
使用 if 條件語句和 **“in”** 關鍵字檢查給定單詞是否出現在上述單詞列表中。
**in** 關鍵字有兩種使用方法:
The in keyword is used to determine whether a value exists in a sequence (list, range, string etc).
如果在相應行中找到給定單詞,則列印行號。
將行號的值增加 1。
使用 **close()** 函式(用於關閉已開啟的檔案)關閉輸入檔案。
它也用於在 for 迴圈中迭代序列
示例
以下程式用於從文字檔案中刪除給定行,並在刪除該行後列印結果檔案內容:
# input text file inputFile = "ExampleTextFile.txt" # storing the current line number lineNumber = 1 # Enter the word givenWord = "TutorialsPoint" print('The word {', givenWord, '} is present in the following lines:') # Opening the given file in read-only mode. with open(inputFile, 'r') as fileData: # Traverse in each line of the file for textline in fileData: # Splitting the line into list of words wordsList = textline.split() # Checking if the given word is present in the above words list if givenWord in wordsList: # Print the line number, if the given word is found print(lineNumber) # Increase the value of linenumber by 1 lineNumber += 1 # Closing the input file fileData.close()
輸出
執行上述程式將生成以下輸出:
The word { TutorialsPoint } is present in the following lines:
1
2
6
在這個程式中,我們讀取了一個包含一些隨機文字的文字檔案。我們建立了一個變數來儲存當前行號並將其初始化為 1,即起始行號。我們逐行遍歷文字檔案,將每一行分解成一個單詞列表,並檢查給定單詞是否在列表中。如果存在,則列印當前行號。對於每一行,行號的值都會增加一。
從本文中,我們學習瞭如何讀取檔案、逐行遍歷檔案以及獲取該行中的所有單詞。獲取單詞後,我們可以反轉單詞、更改大小寫、檢查母音、檢索單詞長度等等。我們還學習瞭如何計算行號以及如何在檔案中搜索單詞,這主要用於一些常見的日常應用程式,例如在結果中查詢姓名、在某些程式碼中搜索關鍵字等等。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP