0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

後で修正

Last updated at Posted at 2024-08-13


import os

# キーワードをwords.txtから読み込む
with open('words.txt', 'r', encoding='utf-8') as file:
    keywords = [line.strip() for line in file.readlines()]

# .txtファイルを取得する
txt_files = [f for f in os.listdir() if f.endswith('.txt')]

def search_keywords_in_txt(txt_file, keywords):
    """
    指定されたtxtファイル内でキーワードを検索し、各キーワードに対して最大3行の結果を返す。
    
    Args:
    txt_file (str): 読み込むtxtファイルのパス
    keywords (list): 検索するキーワードのリスト
    
    Returns:
    dict: キーワードごとに対応する検索結果の辞書
    """
    result = {}

    # ファイルを読み込む
    with open(txt_file, 'r', encoding='utf-8') as file:
        lines = file.readlines()

    # 各キーワードについて検索
    for keyword in keywords:
        result[keyword] = []
        count = 0
        for line in lines:
            if keyword in line:
                result[keyword].append(line.strip())
                count += 1
                # 1キーワードにつき最大3行まで抽出
                if count >= 3:
                    break
    
    return result

# 結果をoutput.txtにフォーマットして出力する
with open('output.txt', 'w', encoding='utf-8') as output_file:
    for txt_file in txt_files:
        # テキストファイル名を出力
        output_file.write(f'■読み取り対象のドキュメントファイル名: {txt_file}\n')
        search_results = search_keywords_in_txt(txt_file, keywords)
        
        for keyword, sentences in search_results.items():
            if sentences:
                # キーワードを出力
                output_file.write(f'●キーワード: {keyword}\n')
                for idx, sentence in enumerate(sentences, 1):
                    # 各結果を出力
                    output_file.write(f'  {idx}. {sentence}\n')
        
        output_file.write('\n')
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?