0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Wordにコメントを挿入したい

Last updated at Posted at 2024-07-24
import sys

# モジュールが存在するディレクトリのパスを指定
module_paths = [
    r"C:\path\to\your\first\module_directory",
    r"C:\path\to\your\second\module_directory"
]

# sys.pathに追加
sys.path.extend(module_paths)

# 例: カスタムモジュールのインポート
try:
    import custom_module  # 追加したディレクトリに存在するモジュール
except ImportError as e:
    print(f"モジュールのインポートに失敗しました: {e}")

# あなたのコード
import win32com.client

def load_keywords(file_path):
    keywords = {}
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            parts = line.strip().split(',')
            if len(parts) > 1:
                keywords[parts[0]] = parts[1:]
            else:
                keywords[parts[0]] = []
    return keywords

def add_comments_to_word(doc_path, keywords):
    try:
        word_app = win32com.client.Dispatch("Word.Application")
    except Exception as e:
        print(f"Wordを起動できませんでした: {e}")
        return None
    
    try:
        word_app.Visible = True
        doc = word_app.Documents.Open(doc_path)
        
        for keyword, variants in keywords.items():
            find = word_app.Selection.Find
            find.Text = keyword
            find.MatchCase = False
            find.MatchWholeWord = True
            find.Execute()

            while find.Found:
                comment_text = "【表記ゆれ】\n" + "\n".join(variants)
                word_app.Selection.Range.Comments.Add(Range=word_app.Selection.Range, Text=comment_text)
                find.Execute()
        
        output_path = doc_path.replace(".docx", "_commented.docx")
        doc.SaveAs(output_path)
        doc.Close()
        word_app.Quit()
        return output_path
    
    except Exception as e:
        print(f"エラーが発生しました: {e}")
        if 'doc' in locals():
            doc.Close(False)
        word_app.Quit()
        return None

# キーワードファイルとWordファイルのパス
keywords_file_path = 'keywords.txt'
word_file_path = 'sample.docx'

# キーワードの読み込み
keywords = load_keywords(keywords_file_path)

# コメントの挿入
output_path = add_comments_to_word(word_file_path, keywords)

if output_path:
    print(f"コメントを挿入したWordファイル: {output_path}")
else:
    print("コメントの挿入に失敗しました。")

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?