※このページではアフィリエイト広告を利用しています

【Python応用】txtファイルから任意の文字列を探索する方法

Python

日常的にPythonを使ってファイル操作を行う中で、特定の文字列をファイルから探したい場面が非常に多いと思います。例えば、ログファイルの中からエラーメッセージを探したり、メモ書きのテキストからキーワードを探したりする場合などあると思います。

ここでは、Pythonに標準搭載されている find() メソッドを使って、.txt ファイル内から特定の文字列を探索する方法を紹介しています。

この記事の対象

  • 文字探索の概要を知りたい方
  • txtデータ内の文字探索を行いたい方
  • find()関数の使用方法を知りたい方
スポンサーリンク
スポンサーリンク

find()メソッドとは?

find() メソッドは、文字列内に指定した文字列が存在するかを調べるための組み込み関数です。

text = "Hello, Python!"
position = text.find("Python")
print(position)  

find() は一致した最初のインデックスを返します。

見つからなかった場合は -1 を返します。

結果

7

find()メソッドについて別記事でも解説しています。以下をご参照下さい。

>>>文字検索-find()メソッド-

.txtファイルから文字列を探索する基本構文

それでは、実際に .txt ファイル内から文字列を探索する簡単な例になります。

予め.txtファイルを準備しておきます。ここでは、以下のような任意のファイル(sample.txt)を用意しています。

This is a test log.
Everything is working fine.
Warning: something might be wrong.
Error: failed to load configuration.
Another line with error detected.

AttributeError: 'int' object has no attribute 'append'
SyntaxError: expected ':'

ファイルから「error」という文字列を探す

keyword = "error"

with open("sample.txt", mode="r", encoding="utf-8") as file
    for line_number, line in enumerate(file, start=1):
        position = line.find(keyword)
        if position != -1:
            print(f"'{keyword}' を {line_number} 行目の {position} 文字目に発見: {line.strip()}")

open("sample.txt", mode="r"): 読み取りモードでテキストファイルを開いています。

enumerate(file, start=1): 各行の行番号を取得しています(1行目からスタート)。

line.find(keyword): 指定のキーワードがその行に含まれているかどうかを確認しています。

position != -1: -1でなければ文字列が見つかったことを示しています。

結果

'error' を 5 行目の 18 文字目に発見: Another line with error detected.

大文字・小文字を無視して探索

find() メソッドは 大文字と小文字を区別 します。たとえば "Error""error" は異なるものと判断されます。

以下の例では、大文字・小文字を無視した探索するプログラムになります。

keyword = "error"

with open("sample.txt", mode="r", encoding="utf-8") as file:
    for line_number, line in enumerate(file, start=1):
        position = line.lower().find(keyword.lower())
        if position != -1:
            print(f"'{keyword}' を {line_number} 行目に発見: {line.strip()}")

.lower()を用いることで全ての文字列を小文字化しています。それから、該当する文字を探索していますので、大文字のキーワードも探索で引っかかるようになります。

以下では、.lower()に関して詳しく解説しています。ご参照下さい。

>>>文字列の小文字/大文字変換-lower()、upper()-

結果

'error' を 4 行目に発見: Error: failed to load configuration.
'error' を 5 行目に発見: Another line with error detected.
'error' を 6 行目に発見: AttributeError: 'int' object has no attribute 'append'
'error' を 7 行目に発見: SyntaxError: expected ':'

複数のキーワードを一度に探索

keywords = ["attribute", "warning", "Syntax"]

with open("sample.txt", mode="r", encoding="utf-8") as file:
    for line_number, line in enumerate(file, start=1):
        for keyword in keywords:
            if line.lower().find(keyword.lower()) != -1:
                print(f"'{keyword}' を {line_number} 行目に発見: {line.strip()}")

ここでは、複数のキーワードをリスト化して、それぞれ探索しています。

結果

'warning' を 3 行目に発見: Warning: something might be wrong.
'attribute' を 7 行目に発見: AttributeError: 'int' object has no attribute 'append'
'Syntax' を 8 行目に発見: SyntaxError: expected ':'

検索結果を別ファイルに書き出す

keyword = "error"

with open("sample.txt", mode="r", encoding="utf-8") as infile, \
     open("results.txt", mode="w", encoding="utf-8") as outfile:
    
    for line_number, line in enumerate(infile, start=1):
        position = line.lower().find(keyword.lower())
        if position != -1:
            result = f"{line_number} 行目: {line}"
            outfile.write(result)

results.txt には一致した行だけが保存されます。

結果

4 行目: Error: failed to load configuration.
5 行目: Another line with error detected.
7 行目: AttributeError: 'int' object has no attribute 'append'
8 行目: SyntaxError: expected ':'

出力した「tesults.txt」の結果です。

まとめ

Pythonの find() メソッドは、簡単に文字列の探索ができる非常に便利な機能です。.txt ファイルと組み合わせて使うことで、ログ検索やデータ解析など、さまざまなシーンに応用できます。

もしより高度なテキスト解析やパターンマッチングを行いたい場合は、Pythonの re(正規表現)モジュールを使用する方法もあります。find() よりも探索の応用が効きます。

おすすめの書籍

  • スッキリわかるPython入門
  • Python ゼロからはじめるプログラミング
  • 面白くてやみつきになる! 文系も超ハマる数学 (青春新書プレイブックス)
タイトルとURLをコピーしました