部分と全体

知識の巣窟

PythonでObsidianのノートに一気にタグをつける

Obsidianを使っている方にはおなじみの課題かもしれませんが、検索したキーワードに対して一つ一つタグやリンクをつけるのは手間ですよね。そんな悩みを解消するPythonスクリプトを作りました。一度実行するだけで、あなたのノートに対して自動的にタグやリンクを追加します。何回か実行することで、ノート同士の関連性がより明確になり、便利になります。 (追記:サブフォルダーまで検索できるようにしました)

使用しているライブラリは、os, globです。 globが入っていない場合は

pip install glob

でインストールしてからご使用ください

##This code will search for each keyword in the keywords list,
##and if it is found in a line of text, it will append the corresponding
##tag from the tags list to that line. Note that the tags list should have
##the same number of elements as the keywords list, and the tags should be
##in the same order as the keywords.

## CAUTION ############################################
## Please back up your obsidian MD files before running

import glob
import os

# Path to folder
folder_path = 'please write full folder path here'

# Get list of text files
# text_files = glob.glob(folder_path + '\*.md') #seek only folder_path
text_files = glob.glob(os.path.join(folder_path, '**', '*.md'), recursive=True) #seek all subfolders

# Set keywords and corresponding tags (1-to-1 relation)
keywords = ['Apple', 'Orange','Banana', '2017', '2018', '2019', '2020', '2021', '2022', '2023', '2024']
tags = [' #Apple',' #Orange',' #Banana',' [[2017]]',' [[2018]]',' [[2019]]',' [[2020]]',' [[2021]]',' [[2022]]', ' [[2023]]', ' [[2024]]']

# Process each text file
for file_path in text_files:
    # Read text file
    with open(file_path, 'r', encoding='utf-8') as f:
        text = f.read()

    # Process text (example: adding tags to end of lines containing keywords)
    lines = text.split('\n')
    for i, line in enumerate(lines):
        for j, keyword in enumerate(keywords):
            if keyword in line:
                lines[i] = line + tags[j]               
                #To show which files were edited
                print(f'Modified file: {file_path} Added:{keyword}')
    text = '\n'.join(lines)

    # Write text to file
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(text)