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-01
import os
import win32com.client as win32

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

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

def search_keywords_in_docx(docx_file, keywords):
    """
    指定されたdocxファイル内でキーワードを検索し、各キーワードに対して最大3行の結果を返す。
    
    Args:
    docx_file (str): 読み込むdocxファイルのパス
    keywords (list): 検索するキーワードのリスト
    
    Returns:
    dict: キーワードごとに対応する検索結果の辞書
    """
    # Wordアプリケーションを起動
    word = win32.gencache.EnsureDispatch('Word.Application')
    # ドキュメントを開く
    doc = word.Documents.Open(os.path.abspath(docx_file))
    result = {}
    
    for keyword in keywords:
        result[keyword] = []
        find = doc.Content.Find
        find.Text = keyword
        
        count = 0
        while find.Execute() and count < 3:
            # 検索結果の範囲を取得
            found_range = find.Parent
            # 段落のテキストを取得
            if found_range.Paragraphs.Count > 0:
                para = found_range.Paragraphs(1).Range.Text.strip()
                if para not in result[keyword]:
                    result[keyword].append(para)
                    count += 1
            # 表のセルのテキストを取得
            elif found_range.Tables.Count > 0:
                table = found_range.Tables(1)
                for row in table.Rows:
                    for cell in row.Cells:
                        cell_text = cell.Range.Text.strip()
                        if keyword in cell_text and cell_text not in result[keyword]:
                            result[keyword].append(cell_text)
                            count += 1
                            if count >= 3:
                                break
                    if count >= 3:
                        break
    
    # ドキュメントを閉じる
    doc.Close(False)
    # Wordアプリケーションを終了
    word.Quit()
    return result

# 結果をoutput.txtにフォーマットして出力する
with open('output.txt', 'w', encoding='utf-8') as output_file:
    for docx_file in docx_files:
        # ドキュメントファイル名を出力
        output_file.write(f'■読み取り対象のドキュメントファイル名: {docx_file}\n')
        search_results = search_keywords_in_docx(docx_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?