the_silver_searcherをインストールして使用することをお勧めします。
私のテストでは、約 2900 万行の約 1GB のテキスト ファイルを検索し、わずか 00h 00m 00.73 秒、つまり 1 秒未満で数百の検索語エントリを見つけました。
これを使用して単語を検索し、見つかった回数をカウントする Python 3 コードを次に示します。
import subprocess
word = "some"
file = "/path/to/some/file.txt"
command = ["/usr/local/bin/ag", "-wc", word, file]
output = subprocess.Popen(command, stdout=subprocess.PIPE).stdout.read()
print("Found entries:", output.rstrip().decode('ascii'))
このバージョンは単語を検索し、行番号と実際のテキストを出力します。単語が見つかった場合:
import subprocess
word = "some"
file = "/path/to/some/file.txt"
command = ["/usr/local/bin/ag", "-w", word, file]
output = subprocess.Popen(command, stdout=subprocess.PIPE)
for line in output.stdout.readlines():
print(line.rstrip().decode('ascii'))