
【Python 100日チャレンジ】Day 42 - テキストファイル高度な処理
「ログファイルから特定のエラーだけ抜き出したい...」 「大きいファイルを開いたらPCがフリーズした...」 「100個のファイルからメールアドレスを一括で抽出できないかな...」
こんな経験、ありませんか?
今日学ぶ正規表現とストリーミング処理をマスターすれば、こんなことができるようになります!
✨ Before → After
手作業で1時間 → Pythonで10秒
メモリ不足でクラッシュ → 10GBファイルもサクサク処理
「このパターンどこ?」 → 一瞬で全件抽出
Day 41で学んだファイル基礎をもとに、
今日は実務で本当に使えるテクニックを身につけましょう!
(完読:35-45分 ⭐⭐⭐)
🎯 今日の学習目標
正規表現でファイルを処理する
大容量ファイルを効率的に処理する
ファイル検索とフィルタリングを行う
実践的なテキスト変換パターンを習得する
実践例題と活用方法を学ぶ
📚 事前知識
Day 41: ファイル入出力の基礎 - ファイルを開く、読む、書く、with文
Day 6: 文字列を扱う (str) - 文字列メソッドと操作
Day 9: 繰り返し文for - ファイルの各行を順番に処理する
🎯 学習目標 1: 正規表現でファイルを処理する
正規表現(Regular Expression)とは?
正規表現は文字列から特定のパターンを見つける強力なツールです。最初は複雑に見えますが、基本文法さえ分かれば非常に便利です!
基本パターン文字:
\d - 数字1つ (0-9)、例: \d\d\d → "123"
\s - 空白文字、例: hello\sworld → "hello world"
+ - 前のパターンが1個以上、例: \d+ → "123", "4567"
* - 前のパターンが0個以上、例: ab* → "a", "ab", "abbb"
[] - 文字集合、例: [a-z] → 小文字1つ
{n} - 正確にn個繰り返し、例: \d{3} → "010"
{n,m} - n個以上m個以下、例: \d{2,4} → "12", "123", "1234"
r'' (Raw String) 文法:
# r''はバックスラッシュ(\)をそのまま使用します
pattern = r'\d+' # ✅ 推奨: Raw String
pattern = '\\d+' # 同じ意味だが複雑💡 ポイント:正規表現パターンは常に r'' 形式で書きましょう!
reモジュール基礎
import re
# 正規表現パターン
email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
phone_pattern = r'\d{3}-\d{4}-\d{4}'
url_pattern = r'https?://[^\s]+'
text = """
連絡先: tanaka@example.com, 090-1234-5678
ウェブサイト: https://example.com
"""
# メール検索
emails = re.findall(email_pattern, text)
print(f"メール: {emails}")
# 電話番号検索
phones = re.findall(phone_pattern, text)
print(f"電話番号: {phones}")
# URL検索
urls = re.findall(url_pattern, text)
print(f"URL: {urls}")ファイルからパターン抽出
def extract_emails(filename):
"""ファイルからすべてのメールアドレスを抽出"""
email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
emails = []
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
found = re.findall(email_pattern, line)
emails.extend(found)
# 重複除去
return list(set(emails))
# 使用例
# emails = extract_emails("contacts.txt")
# for email in emails:
# print(email)ログファイルパース
import re
from datetime import datetime
def parse_log_file(filename):
"""Apacheスタイルのログをパース"""
# ログパターン: IP - - [日付] "リクエスト" ステータスコード サイズ
pattern = r'(\d+\.\d+\.\d+\.\d+).*\[(.*?)\].*"(.*?)".*(\d{3})'
logs = []
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
match = re.search(pattern, line)
if match:
ip, timestamp, request, status = match.groups()
logs.append({
'ip': ip,
'timestamp': timestamp,
'request': request,
'status': int(status)
})
return logs
# 使用例
# logs = parse_log_file("access.log")
#
# # 404エラーのみフィルタリング
# errors_404 = [log for log in logs if log['status'] == 404]
# print(f"404エラー: {len(errors_404)}件")テキスト置換
def clean_text_file(input_file, output_file):
"""テキストファイル整理(空白、特殊文字など)"""
with open(input_file, 'r', encoding='utf-8') as fin, \
open(output_file, 'w', encoding='utf-8') as fout:
for line in fin:
# 複数の空白を1つに
line = re.sub(r'\s+', ' ', line)
# 前後の空白除去
line = line.strip()
# 空行は除外
if line:
fout.write(line + '\n')
# 使用
# clean_text_file("messy.txt", "clean.txt")🎯 学習目標 2: 大容量ファイルを効率的に処理する
メモリ効率的な読み込み
def count_lines_efficient(filename):
"""大容量ファイルの行数を数える(メモリ効率的)"""
count = 0
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
count += 1
return count
# 比較: 非効率的な方法
def count_lines_inefficient(filename):
"""❌ メモリ非効率的(ファイル全体をロード)"""
with open(filename, 'r', encoding='utf-8') as f:
lines = f.readlines() # 全体をメモリに!
return len(lines)
# 1GBのファイルも効率的に処理
# print(f"行数: {count_lines_efficient('huge_file.txt'):,}")チャンク単位処理
def process_large_file(filename, chunk_size=1024*1024):
"""大容量ファイルをチャンク単位で処理"""
with open(filename, 'r', encoding='utf-8') as f:
while True:
chunk = f.read(chunk_size) # 1MBずつ読み込み
if not chunk:
break
# チャンク処理
process_chunk(chunk)
def process_chunk(chunk):
"""チャンクデータ処理の例"""
# 例: 特定の単語の数を数える
word_count = chunk.lower().count('python')
print(f"このチャンクで'python': {word_count}個")ストリーミング方式処理
def stream_process(input_file, output_file, transform_func):
"""ストリーミング方式でファイル変換"""
with open(input_file, 'r', encoding='utf-8') as fin, \
open(output_file, 'w', encoding='utf-8') as fout:
for line in fin:
# 各行を変換
transformed = transform_func(line)
fout.write(transformed)
# 使用例: すべてのテキストを大文字に
def to_upper(line):
return line.upper()
# stream_process("input.txt", "output.txt", to_upper)実践: 大容量ログ分析
from collections import defaultdict # デフォルト値を持つ辞書
def analyze_large_log(filename):
"""大容量ログファイル分析(ストリーミング)"""
# defaultdict(int)は存在しないキーにアクセスすると自動的に0を生成
# 通常の辞書と違いKeyErrorが発生しないので便利です
stats = {
'total_lines': 0,
'status_codes': defaultdict(int), # {'200': 0, '404': 0, ...} 自動生成
'top_ips': defaultdict(int) # {'192.168.1.1': 0, ...} 自動生成
}
# 正規表現パターン
pattern = r'(\d+\.\d+\.\d+\.\d+).*".*"\s+(\d{3})'
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
stats['total_lines'] += 1
match = re.search(pattern, line)
if match:
ip, status = match.groups()
stats['status_codes'][status] += 1
stats['top_ips'][ip] += 1
# 進捗状況出力(10万行ごと)
if stats['total_lines'] % 100000 == 0:
print(f"処理中... {stats['total_lines']:,}行")
# 上位10個のIP
top_10_ips = sorted(stats['top_ips'].items(),
key=lambda x: x[1],
reverse=True)[:10]
print(f"\n合計 {stats['total_lines']:,}行分析完了")
print("\nステータスコード分布:")
for code, count in sorted(stats['status_codes'].items()):
print(f" {code}: {count:,}回")
print("\n上位10個のIP:")
for ip, count in top_10_ips:
print(f" {ip}: {count:,}回")
# 使用
# analyze_large_log("access.log")🎯 学習目標 3: ファイル検索とフィルタリングを行う
grep実装(テキスト検索)
def grep(pattern, filename, ignore_case=False, line_numbers=False):
"""Unix grepコマンド実装"""
flags = re.IGNORECASE if ignore_case else 0
compiled_pattern = re.compile(pattern, flags)
matches = []
with open(filename, 'r', encoding='utf-8') as f:
for line_num, line in enumerate(f, 1):
if compiled_pattern.search(line):
if line_numbers:
matches.append((line_num, line.strip()))
else:
matches.append(line.strip())
return matches
# 使用例
pattern = r'error'
matches = grep(pattern, 'app.log', ignore_case=True, line_numbers=True)
print(f"'{pattern}' 発見: {len(matches)}件")
for line_num, line in matches[:10]: # 上位10件のみ
print(f"{line_num:4d}: {line}")複数ファイルで検索
import os
def search_in_files(pattern, directory, extension='.txt'):
"""ディレクトリ内のすべてのファイルでパターン検索"""
results = {}
for filename in os.listdir(directory):
if filename.endswith(extension):
filepath = os.path.join(directory, filename)
matches = grep(pattern, filepath, line_numbers=True)
if matches:
results[filename] = matches
return results
# 使用
# results = search_in_files(r'TODO', './src', extension='.py')
#
# for filename, matches in results.items():
# print(f"\n📄 {filename}: {len(matches)}件")
# for line_num, line in matches[:3]:
# print(f" {line_num}: {line}")条件付きフィルタリング
def filter_file(input_file, output_file, condition):
"""条件に合う行のみ抽出"""
with open(input_file, 'r', encoding='utf-8') as fin, \
open(output_file, 'w', encoding='utf-8') as fout:
for line in fin:
if condition(line):
fout.write(line)
# 使用例1: ERRORを含む行のみ
# filter_file('app.log', 'errors.log', lambda line: 'ERROR' in line)
# 使用例2: 空行を除外
# filter_file('messy.txt', 'clean.txt', lambda line: line.strip())
# 使用例3: 特定の日付のみ
# filter_file('access.log', '2025-04-11.log',
# lambda line: '2025-04-11' in line)🎯 学習目標 4: 実践的なテキスト変換パターンを習得する
大文字小文字変換
def convert_case(input_file, output_file, mode='upper'):
"""大文字小文字変換"""
with open(input_file, 'r', encoding='utf-8') as fin, \
open(output_file, 'w', encoding='utf-8') as fout:
for line in fin:
if mode == 'upper':
fout.write(line.upper())
elif mode == 'lower':
fout.write(line.lower())
elif mode == 'title':
fout.write(line.title())
elif mode == 'capitalize':
fout.write(line.capitalize())
# convert_case('input.txt', 'output.txt', mode='upper')文字置換
def replace_in_file(input_file, output_file, replacements):
"""ファイル内の複数文字列を同時置換"""
with open(input_file, 'r', encoding='utf-8') as fin, \
open(output_file, 'w', encoding='utf-8') as fout:
for line in fin:
# すべての置換ルールを適用
for old, new in replacements.items():
line = line.replace(old, new)
fout.write(line)
# 使用例
replacements = {
'colour': 'color',
'favourite': 'favorite',
'centre': 'center'
}
# replace_in_file('british.txt', 'american.txt', replacements)正規表現置換
def regex_replace(input_file, output_file, pattern, replacement):
"""正規表現ベースの置換"""
compiled = re.compile(pattern)
with open(input_file, 'r', encoding='utf-8') as fin, \
open(output_file, 'w', encoding='utf-8') as fout:
for line in fin:
new_line = compiled.sub(replacement, line)
fout.write(new_line)
# 使用例: メールマスキング
# pattern = r'([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})'
# replacement = r'\1@***'
# regex_replace('contacts.txt', 'masked.txt', pattern, replacement)行ソート
def sort_file_lines(input_file, output_file, reverse=False):
"""ファイルの行をソート"""
with open(input_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
# ソート
sorted_lines = sorted(lines, reverse=reverse)
with open(output_file, 'w', encoding='utf-8') as f:
f.writelines(sorted_lines)
# sort_file_lines('unsorted.txt', 'sorted.txt')🎯 学習目標 5: 実践例題と活用方法を学ぶ
例題 1: コード統計分析器
import os
def analyze_code_directory(directory, extensions=('.py', '.js', '.java')):
"""コードディレクトリ統計分析"""
stats = {
'total_files': 0,
'total_lines': 0,
'total_code_lines': 0,
'total_comment_lines': 0,
'total_blank_lines': 0,
'files_by_ext': {}
}
for root, dirs, files in os.walk(directory):
for filename in files:
if filename.endswith(extensions):
filepath = os.path.join(root, filename)
ext = os.path.splitext(filename)[1]
# ファイル分析
file_stats = analyze_code_file(filepath)
# 統計更新
stats['total_files'] += 1
stats['total_lines'] += file_stats['total']
stats['total_code_lines'] += file_stats['code']
stats['total_comment_lines'] += file_stats['comment']
stats['total_blank_lines'] += file_stats['blank']
if ext not in stats['files_by_ext']:
stats['files_by_ext'][ext] = 0
stats['files_by_ext'][ext] += 1
# 結果出力
print("\n📊 コード統計")
print("=" * 60)
print(f"総ファイル: {stats['total_files']}個")
print(f"総行数: {stats['total_lines']:,}行")
print(f" • コード: {stats['total_code_lines']:,}行")
print(f" • コメント: {stats['total_comment_lines']:,}行")
print(f" • 空行: {stats['total_blank_lines']:,}行")
print("\n拡張子別:")
for ext, count in stats['files_by_ext'].items():
print(f" {ext}: {count}個")
return stats
def analyze_code_file(filepath):
"""単一コードファイル分析"""
stats = {'total': 0, 'code': 0, 'comment': 0, 'blank': 0}
try:
with open(filepath, 'r', encoding='utf-8') as f:
for line in f:
stats['total'] += 1
stripped = line.strip()
if not stripped:
stats['blank'] += 1
elif stripped.startswith('#') or stripped.startswith('//'):
stats['comment'] += 1
else:
stats['code'] += 1
except Exception as e:
print(f"⚠️ {filepath} 分析失敗: {e}")
return stats
# 使用
# analyze_code_directory('./my_project')例題 2: マークダウン目次生成器
def generate_toc(markdown_file):
"""マークダウンファイルから目次(TOC)生成"""
toc = []
heading_pattern = r'^(#{1,6})\s+(.+)$'
with open(markdown_file, 'r', encoding='utf-8') as f:
for line in f:
match = re.match(heading_pattern, line)
if match:
level = len(match.group(1)) # #の数
title = match.group(2).strip()
# アンカー生成(空白 -> ハイフン、小文字)
anchor = title.lower().replace(' ', '-')
anchor = re.sub(r'[^\w-]', '', anchor)
# インデント
indent = ' ' * (level - 1)
toc.append(f"{indent}- [{title}](#{anchor})")
return '\n'.join(toc)
# 使用例
# toc = generate_toc('README.md')
# print("## 目次\n")
# print(toc)例題 3: CSV to Markdown テーブル変換
def csv_to_markdown(csv_file, output_file):
"""CSVファイルをマークダウンテーブルに変換"""
with open(csv_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
if not lines:
return
# ヘッダー
header = lines[0].strip().split(',')
# マークダウンテーブル生成
with open(output_file, 'w', encoding='utf-8') as f:
# ヘッダー行
f.write('| ' + ' | '.join(header) + ' |\n')
# 区切り線
f.write('|' + '---|' * len(header) + '\n')
# データ行
for line in lines[1:]:
row = line.strip().split(',')
f.write('| ' + ' | '.join(row) + ' |\n')
# 使用
# csv_to_markdown('data.csv', 'table.md')💡 実践のコツと注意点
Tip 1: 大容量ファイルはストリーミングで処理しましょう
# ❌ 悪い例: 全体をメモリにロード
with open("huge.log", "r", encoding="utf-8") as f:
content = f.read() # メモリ不足の危険!
for line in content.splitlines():
process(line)
# ✅ 良い例: 1行ずつストリーミング
with open("huge.log", "r", encoding="utf-8") as f:
for line in f: # メモリ効率的!
process(line.strip())理由: 大容量ファイルを一度に読むとメモリ不足になる可能性があります。
Tip 2: 正規表現はコンパイルして再利用しましょう
# ❌ 悪い例: 毎回コンパイル
for line in file:
if re.search(r'\d{3}-\d{4}', line): # 毎回コンパイル!
process(line)
# ✅ 良い例: 一度だけコンパイル
pattern = re.compile(r'\d{3}-\d{4}')
for line in file:
if pattern.search(line): # 高速!
process(line)理由: 正規表現のコンパイルはコストが高いので、再利用すると性能が向上します。
Tip 3: ファイルポインタ使用時はバイナリモードを活用しましょう
# ❌ テキストモードでのseekは制限的
with open("data.txt", "r") as f:
f.seek(100) # 正確でない可能性あり(エンコーディング問題)
# ✅ バイナリモードで正確なseek
with open("data.txt", "rb") as f:
f.seek(100) # 正確なバイト位置
data = f.read()理由: テキストモードではエンコーディングのためバイト位置が正確でない場合があります。
🧪 練習問題
問題 1: 重複行削除
ファイルから重複した行を削除する関数を作成してください。(順序維持)
💡 ヒント: set を使って見た行を追跡しましょう。
✅ 解答
def remove_duplicates(input_file, output_file):
"""重複行削除(順序維持)"""
seen = set()
with open(input_file, 'r', encoding='utf-8') as fin, \
open(output_file, 'w', encoding='utf-8') as fout:
for line in fin:
if line not in seen:
seen.add(line)
fout.write(line)
# テスト
remove_duplicates('with_duplicates.txt', 'unique.txt')問題 2: 単語頻度 Top 10
ファイルで最も多く出現した単語10個を見つけてください。
💡 ヒント: collections.Counter と re.findall() を活用しましょう。
✅ 解答
from collections import Counter
import re
def top_words(filename, n=10):
"""最も多く出現した単語N個"""
word_count = Counter()
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
# 単語抽出(アルファベットのみ)
words = re.findall(r'\b[a-zA-Z]+\b', line.lower())
word_count.update(words)
print(f"上位 {n}個の単語:")
for word, count in word_count.most_common(n):
print(f" {word:15s}: {count:,}回")
# テスト
top_words('article.txt')問題 3: ファイル逆順出力
ファイルの内容を逆順で出力する関数を作成してください。(大容量ファイル考慮)
💡 ヒント: 小さいファイルは readlines()、大容量はファイルポインタを活用しましょう。
✅ 解答
def reverse_file(input_file, output_file):
"""ファイル行順序を逆順に"""
# 小さいファイル
with open(input_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
with open(output_file, 'w', encoding='utf-8') as f:
f.writelines(reversed(lines))
# 大容量ファイル用(メモリ効率的)
def reverse_large_file(input_file, output_file):
"""大容量ファイル逆順"""
# 1. 位置インデックスを保存
positions = []
with open(input_file, 'rb') as f:
positions.append(f.tell())
for line in f:
positions.append(f.tell())
# 2. 逆順で読んで書く
with open(input_file, 'rb') as fin, \
open(output_file, 'wb') as fout:
for i in range(len(positions) - 2, -1, -1):
fin.seek(positions[i])
line = fin.readline()
fout.write(line)📝 今日学んだ内容のまとめ
ファイル高度な処理の核心:
正規表現:パターンマッチングと置換 → re.findall(pattern, text)
ストリーミング処理:大容量ファイルのメモリ効率 → for line in f:
ファイルポインタ:ファイル内の位置移動 → f.seek(position)
チャンク処理:ファイルを部分ごとに読み込み → f.read(chunk_size)
パターンコンパイル:正規表現の再利用 → re.compile(pattern)
核心コードパターン
# 大容量ファイルストリーミング処理
with open("large.txt", "r", encoding="utf-8") as f:
for line in f:
process(line.strip())
# 正規表現活用
import re
pattern = re.compile(r'\d{3}-\d{4}')
matches = pattern.findall(text)
# チャンク単位読み込み
with open("file.bin", "rb") as f:
while True:
chunk = f.read(8192)
if not chunk:
break
process(chunk)🔗 関連資料
📚 前回の学習
前回は、ファイルを開いて、読んで、書く基本方法とwith文を学びました!
📚 次回の学習
次回は、JSONファイルの読み書き、データ変換、ネストされたJSONの処理を学びます!
📚 シリーズをまとめて読む
Python 100日チャレンジの全記事は、
マガジン「Python 100日チャレンジ」 でまとめて読めます 😊
よろしければ、フォローしていただけると嬉しいです!
🚀 遅いと思った時が一番早い時期です!🚀
Day 42/100 | Phase 5:ファイル処理と例外処理 | #100DaysOfPython