2024/08/27

テキスト上の数値をまとめて増減するスクリプト

概要

このツールは、AppleScriptでUI部分を処理し、Pythonで主要コードを処理しています。

ユーザーが指定したパターンに基づいてクリップボードのテキスト内の数字を増減します。

例えば、「(」に続く数字を特定して増減させることができます。この機能は、文書の整形やデータをまとめて処理する際に非常に便利です。

前準備

このツールを使用する前に、必要なライブラリのインストールと環境設定を行う必要があります。以下の手順に従ってください。

pyperclipのインストール

このツールでは、クリップボードの操作にpyperclipライブラリを使用します。まだインストールされていない場合は、以下のコマンドを実行してインストールしてください。

pip install pyperclip

または、Anacondaを使用している場合は、

conda install -c conda-forge pyperclip

を実行してください。

Python インタープリタのパスの確認と変更

スクリプトを実行するためには、正しいPythonインタープリタのパスを指定する必要があります。使用している環境によってパスは異なるため、以下のコマンドをターミナルで実行し、Pythonインタープリタの正確なパスを確認してください。

which python3

このコマンドの出力結果は、例えば /usr/local/bin/python3/opt/anaconda3/bin/python3 など、インストールされている環境によって異なります。このパスは、AppleScriptでスクリプトを実行する際に使用するパスと一致する必要があります。

set command to "/opt/anaconda3/bin/python3 '/Users/testuser/Desktop/pythoncode.py' " & quoted form of prefixPattern & " " & quoted form of suffixPattern & " " & quoted form of adjustment

そこで得たパスをAppleScript上記コードの

/opt/anaconda3/bin/python3

 この部分を置き換えます。またPythonコードを保存したパスとファイル名も

'/Users/testuser/Desktop/pythoncode.py'

この箇所と置き換えます。 


使い方

例:「(3,7),(5,7)」の3と5を+2して「(5,7),(7,7)」にしたい。

  1. 修正したいテキストをコピーしてクリップボードに入れます。
  2. AppleScriptを実行します。
  3. AppleScriptダイアログを通じて、変換したい数字の前か後ろの文字列を入力します。
    これはどちらかだけで大丈夫です。
    例:前に( 、後ろは空欄…これで ( に続く数字がマッチします。
  4. 増減させたい数値を入力します。
    例:2
  5. クリップボード上のテキストが自動的に処理され、結果がクリップボードに戻されます。

・AppleScript


          

-- ユーザーにパターン(前)を入力させる

set prefixPattern to text returned of (display dialog "数字の前にある文字列を入力してください(必須ではありません):" default answer "")

if prefixPattern is "" then set prefixPattern to "none"


-- ユーザーにパターン(後)を入力させる

set suffixPattern to text returned of (display dialog "数字の後にある文字列を入力してください(必須ではありません):" default answer "")

if suffixPattern is "" then set suffixPattern to "none"


-- ユーザーに増減量を入力させる

set adjustment to text returned of (display dialog "増減する数を入力してください:" default answer "")


-- AnacondaPythonを指定してスクリプトを実行するコマンドを構築

set command to "/opt/anaconda3/bin/python3 '/Users/testuser/Desktop/pythoncode.py' " & quoted form of prefixPattern & " " & quoted form of suffixPattern & " " & quoted form of adjustment


-- コマンドを実行し、結果を取得

try

set output to do shell script command

on error errorMessage number errorNumber

display dialog errorMessage buttons {"OK"} default button 1

return

end try


-- 成功した場合、変更箇所の数を表示

display dialog output buttons {"OK"} default button 1



・Python

import re
import sys
import pyperclip

def adjust_numbers_in_text(text, prefix, suffix, adjustment):
if not prefix and not suffix:
return "Error: No pattern provided.", 0

regex_patterns = []
if prefix:
regex_patterns.append(re.escape(prefix) + r'\d+')
if suffix:
regex_patterns.append(r'\d+' + re.escape(suffix))
regex_pattern = rf'({"|".join(regex_patterns)})'

matches = list(re.finditer(regex_pattern, text))
if not matches:
return "Error: No matching numbers found.", 0

adjusted_count = 0
for match in reversed(matches):
full_match = match.group(1)
number_part = re.search(r'\d+', full_match).group()
new_number = int(number_part) + int(adjustment)
new_text = full_match.replace(number_part, str(new_number))
text = text[:match.start()] + new_text + text[match.end():]
adjusted_count += 1
return text, adjusted_count

if __name__ == '__main__':
prefix = sys.argv[1] if sys.argv[1] != 'none' else ''
suffix = sys.argv[2] if sys.argv[2] != 'none' else ''
try:
adjustment = int(sys.argv[3])
except ValueError:
print("Error: Adjustment must be a number.")
sys.exit(1) # 適切な数値でなければエラーとして終了

input_text = pyperclip.paste()
result_text, adjusted_count = adjust_numbers_in_text(input_text, prefix, suffix, adjustment)

if "Error" in result_text:
print(result_text) # エラーメッセージを出力
else:
pyperclip.copy(result_text)
print(f"Processed text has been copied to clipboard. Adjusted {adjusted_count} places.")