如何使用 Python 在文字檔案中搜索字串?


在對文字資料進行資料分析時,在文字檔案中搜索字串是一項重要的任務。在 Python 中,我們可以使用多種方法在文字檔案中搜索字串,例如逐行讀取和搜尋、讀取整個檔案以及使用正則表示式、使用 grep 命令等。

方法 1:逐行讀取和搜尋

一種簡單的方法是逐行讀取文字檔案,並在每一行中搜索所需的字串。此方法適用於較小的文字檔案。

語法

for line in file:
            if search_string in line:
                return True
return False

這裡,for 迴圈遍歷檔案的每一行,並將每個單詞與 search_string 進行比較。如果找到 search_string,則返回 True,否則返回 False。

示例

在下面的示例中,我們定義了一個函式 search_string_line_by_line,它將 file_pathsearch_string 作為引數。該函式使用 open() 函式以 'r' 模式開啟檔案以讀取檔案。它遍歷檔案中的每一行,並使用 in 運算子檢查 search_string 是否存在於該行中。如果找到該字串,則該函式返回 True,表示匹配。如果迴圈完成而沒有找到匹配項,則該函式返回 False。

def search_string_line_by_line(file_path, search_string):
    with open(file_path, 'r') as file:
        for line in file:
            if search_string in line:
                return True
        return False

file_path = 'example.txt'
search_string = 'Python'

if search_string_line_by_line(file_path, search_string):
    print("String found in the text file.")
else:
    print("String not found in the text file.")

輸出

String found in the text file.

方法 2:讀取整個檔案並使用正則表示式

對於較大的文字檔案,將整個檔案讀入記憶體可能效率更高。我們可以使用正則表示式進行模式匹配,包括字串搜尋。

語法

match = re.search(search_string, file_contents)

這裡,re.search() 函式將 search_string 和檔案內容作為引數,並在檔案內容中搜索 search_string。

示例

在下面的示例中,我們匯入 re 模組以利用正則表示式。該函式 search_string_with_regex 將 file_path 和 search_string 作為引數。它開啟檔案,使用 read() 方法讀取其所有內容,並將內容儲存在 file_contents 變數中。然後,它使用 re.search() 函式在 file_contents 中搜索 search_string 模式。如果找到匹配項,則該函式返回 True;否則,返回 False。

import re

def search_string_with_regex(file_path, search_string):
    with open(file_path, 'r') as file:
        file_contents = file.read()
        match = re.search(search_string, file_contents)
        return match is not None

file_path = 'example.txt'
search_string = r'hello\sworld'

if search_string_with_regex(file_path, search_string):
    print("String found in the text file.")
else:
    print("String not found in the text file.")

輸出

String not found in the text file.

方法 3:透過子程序使用 grep 命令

我們可以使用 Python 的 subprocess 模組執行 shell 命令。我們可以利用此 subprocess 模組使用功能強大的 grep 命令列工具在文字檔案中搜索字串。

語法

subprocess.check_output(['grep', search_string, file_path])

這裡,subprocess.check_output() 函式將搜尋字串和檔案路徑作為輸入,並執行 grep 命令以在檔案內容中查詢 search/_string。

示例

在下面的示例中,我們匯入 subprocess 模組以執行 shell 命令。該函式 search_string_with_grep 將 file_path 和 search_string 作為引數。它使用 subprocess.check_output() 函式執行 grep 命令,並將指定的 search_string 和 file_path 作為引數。如果命令成功執行(即找到該字串),則該函式返回 True。否則,返回 False。

import subprocess

def search_string_with_grep(file_path, search_string):
    try:
        subprocess.check_output(['grep', search_string, file_path])
        return True
    except subprocess.CalledProcessError:
        return False

file_path = 'example.txt'
search_string = 'Python'

if search_string_with_grep(file_path, search_string):
    print("String found in the text file.")
else:
    print("String not found in the text file.")

輸出

String found in the text file.

結論

在本文中,我們討論瞭如何在 Python 中使用不同的方法在文字檔案中搜索字串。第一種方法涉及逐行讀取和搜尋,適用於較小的檔案。第二種方法利用正則表示式搜尋整個檔案內容,可以實現更復雜的模式匹配。第三種方法利用 subprocess 模組利用 grep 命令列工具,提供了一種強大而靈活的方法。

更新於: 2023-07-18

7K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告