Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Books
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

タグ: NSMutableSet

CotEditorの最前面のドキュメントの選択範囲を伏せ字に

Posted on 10月 22, 2019 by Takaaki Naganoya

CotEditorの最前面のドキュメントの選択範囲を、簡易形態素解析ルーチンeasyJparseを用いて、いい感じに伏せ字にするAppleScriptです。

–> Download makeSelectionToFuseji(Code-Signed AppleScript applet with libraries in its bundle, co-work with CotEditor)

easyJparseは日本語のコマンド解析用にでっちあげた作った超簡易形態素解析プログラムです。単語(形態素)ごとに分割しますが、品詞まではわかりません。コマンド解釈用ではあるものの、少し他の用途にも使えないかと思い、このような用途に使ってみました。

# 本Scriptは、CotEditor用のScript Pack v2.0に収録されています


▲CotEditorの選択範囲を伏せ字にする。形態素解析して単語化して、単語単位で伏せ字にするかの判断を実行

テキストエディタ上で伏せ字処理というのは、個人的によく使います。たいていは、オリジナルの文章に対して同様の分量の文章を作らなくてはならないようなケースで、文字数の感覚をつかむために使います。一種のダミーレイアウトのようなものです。

本スクリプトのような伏せ字処理については、ニーズがあるんだかないんだか不明なものですが、とりあえず掲載してみました。自分で使ってみたところ、たしかに面白いものの、実用性については未知数という印象です。

(minusList of parseSPD) に入れている語群は、どこかからか拾ってきたもののようではあるものの、すでに何か方向性を見失っているような気がしないではありません。

AppleScript名:選択範囲を伏せ字に(簡易形態素解析でそれっぽく).scptd
— Created 2018-09-26 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5" — El Capitan (10.11) or later
use framework "Foundation"
use scripting additions
use jParser : script "easyJParse"

property NSArray : a reference to current application’s NSArray
property NSMutableSet : a reference to current application’s NSMutableSet
property NSSortDescriptor : a reference to current application’s NSSortDescriptor

property fuesejiChar : "□"

script parseSPD
  property pList : {}
  
property p2List : {}
  
property oneLine : {}
  
property outStr : ""
  
property minusList : {}
end script

–伏せ字化しない助詞などの単語リスト。名詞だけを残すように整備。単語(形態素)単位で照合する
set (minusList of parseSPD) to {"", " ", "ー", "あ", "で", "も", "に", "と", "の", "は", "へ", "さ", "が", "せ", "か", "た", "だ", "だっ", "ば", "つ", "な", "い", "き", "お", "ら", "る", "れ", "なっ", "それ", "これ", "あれ", "どれ", "この", "どの", "あの", "その", "まで", "こと", "もの", "いつ", "いく", "たち", "ただ", "たい", "そう", "いる", "よう", "れる", "ない", "なら", "なる", "なけれ", "から", "する", "たら", "たり", "だけ", "って", "られ", "的", "化", "いくら", "そんな", "どんな", "あんな", "者", "陰", "時", "事", "こんな", "つれ", "けど", "ああ", "ある", "あっ", "あり", "しかし", "きっと", "すっかり", "例えば", "たとえば", "さっぱり", "たとえ", "だろう", "かつ", "ところ", "まるで", "だが", "全て", "すべて", "なり", "いい", "つれ", "つけ", "ながら", "せいぜい", "そうそう", "さらに", "もっと", "まだ", "なく", "し", "を", "て", "いけ", "行く", "また", "まま", "まぁ", "『", "』", "、", "。", "。。", "……。", "【", "】", "「", "」", "(", ")", "最近", "今度", "中", "チカチカ", "グラグラ", "ふわふわ", "少し", "ついで", "より", "っぽい", "ぐらい", "何", "とき", "ため", "そっくり", "そして", "やがて", "じきに", "すぐ", "今", "次", "できる", "出来る", "いや", "そう", "おそらく", "いえ", "らしい", "とも", "ほぼ", "つい", "もう", "きっかけ", "ころ", "頃", "早々", "そこ", "どこ", "なんか", "じゃ", "くれ", "ください", "こそ", "あいつ", "だれ", "誰", "おぼしき", "らしき", "らしい", "しか", "でき", "よっ", "確か", "どう", "こう", "そう", "ああ", "くる", "ざま", "ごとく", "きれ", "はず", "さらに", "さらなる", "更なる", "など", "ごと", "とても", "たく", "いう", "とっ", "いっ", "えっ", "おっ", "ここ", "そこ", "どこ", "なかっ", "ごく", "やる", "ゆい", "ふと", "たび", "ほど", "もた", "よし", "ぜひ", "いら", "よい", "ま", "み", "む", "め", "も", "や", "けれど", "だけど", "したがっ", "すごく", "そもそも", "ほしい", "なれる", "すぎ", "もふもふ", "モフモフ", "さん", "おと", "とー", "えっと", "け", "っけ", "なん", "よ", "ね", "しっくり", "くれる", "くれた", "なぜ", "まあ", "まぁ", "ん", "なんて", "!」"}

set (pList of parseSPD) to {}
set (p2List of parseSPD) to {}
set (oneLine of parseSPD) to {}
set (outStr of parseSPD) to {}

tell application "CotEditor"
  tell front document
    –選択部分が存在しているかどうかチェック
    
set aCon to contents of selection
    
if aCon = "" then return
    
    
set (pList of parseSPD) to paragraphs of aCon
  end tell
end tell

–伏せ字にする対象単語を、助詞などを消し込むことでピックアップ
repeat with i in (pList of parseSPD)
  if length of i > 1 then
    –簡易形態素解析
    
set tempList to parseJ(i) of jParser
    
    
–簡易形態素解析したリストと助詞などのリストの差分を計算
    
set cList to clacListDiff(tempList, (minusList of parseSPD)) of me
    
    
set (oneLine of parseSPD) to {}
    
repeat with ii in tempList
      set aLen to length of ii
      
if ii is in cList then
        –伏せ字化する場合
        
set bCon to multipleChar(fuesejiChar, aLen) of me
        
      else
        –そのまま出力する場合
        
set bCon to contents of ii
      end if
      
set the end of (oneLine of parseSPD) to bCon
    end repeat
    
    
–1つの文章ぶんの単語を連結
    
set cStr to retDelimedText((oneLine of parseSPD), "") of me
  else
    set cStr to ""
  end if
  
  
set the end of (p2List of parseSPD) to cStr
  
end repeat

–すべての文章を連結して配列からテキストに
set (outStr of parseSPD) to retDelimedText((p2List of parseSPD), return) of me

tell application "CotEditor"
  tell front document
    set contents of selection to (outStr of parseSPD)
  end tell
end tell

–指定文字を指定回数繰り返して連結して出力
on multipleChar(aChar as string, aLen as integer)
  set aList to {}
  
repeat aLen times
    set the end of aList to aChar
  end repeat
  
  
return retDelimedText(aList, "") of me
end multipleChar

–1D Listを要素間に指定デリミタをはさんで文字列化
on retDelimedText(aList as list, aDelim as string)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set aText to aList as text
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retDelimedText

–2つの1D Listの差分を計算
on clacListDiff(aList as list, bList as list)
  set aSet to NSMutableSet’s setWithArray:aList
  
set bSet to NSMutableSet’s setWithArray:bList
  
  
aSet’s minusSet:bSet –補集合
  
set aRes to aSet’s allObjects() as list
  
  
return aRes
end clacListDiff

★Click Here to Open This Script 

Posted in list Natural Language Processing Text | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy CotEditor NSArray NSMutableSet NSSortDescriptor | 1 Comment

アイテム番号リストをもとに、ヒットしなかった項目を返す

Posted on 7月 31, 2019 by Takaaki Naganoya

アイテム番号の入ったリスト(配列変数)をもとに、ヒットしなかった項目を返すというAppleScriptです。

これは、なにがしかのデータとなにがしかの書類上に配置されたデータの照合を行って、存在が確認されなかったデータの一覧を作成するために作成したものです。

存在確認といえば、たいていは「存在していたデータそのもの、あるいはデータのアイテム番号一覧」といったものを出力するようになっています。そこに、「存在が確認できなかったデータの一覧が欲しい」という要望が出てくることも、だいたいは普通の出来事です。

ただ、この手の「言語化すると大したことはないが、実施に精神的な抵抗感をおぼえる処理」といいいますか、「後片付け的な処理」というのは、書くのが面倒で後回しになりがちなものでもあります。

事実、実際に書いてみたら、、、既存のサブルーチンの組み合わせで作りましたが、1日たって見直してみると何が書いてあるのかよく思い出せないレベルです(既存のサブルーチンの組み合わせが過ぎて、意味がわかりにくいのかも)。

AppleScript名:アイテム番号リストをもとに、ヒットしなかった項目を返す.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/07/29
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—

property NSArray : a reference to current application’s NSArray
property NSMutableSet : a reference to current application’s NSMutableSet
property NSMutableArray : a reference to current application’s NSMutableArray

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set strList to {"Apple", "Book", "Cheeze", "Dictionary", "Escalgo", "Find", "Gorila", "hook", "ink", "jet"}
set hitIDList to {1, 2, 3, 4, 6}

set bList to getUnpickedContents(hitIDList, strList) of me
–> {"Escalgo", "Gorila", "hook", "ink", "jet"}

on getUnpickedContents(aList, strList)
  set aMax to length of strList
  
set bList to getSequentialNumList(aMax) of me
  
set cList to excludeTwoList(bList, aList) of me
  
  
set anArray to NSMutableArray’s arrayWithArray:(cList)
  
set dList to (anArray’s sortedArrayUsingSelector:"compare:") as list
  
  
set eList to retConListFromItemNumList(dList, strList) of me
  
return eList
end getUnpickedContents

–アイテム項目番号が入っているリストをもとに、中身が入っているリストから項目を取り出す
on retConListFromItemNumList(dList, strList)
  set outList to {}
  
repeat with i in dList
    set aTmp to item (contents of i) of strList
    
set the end of outList to aTmp
  end repeat
  
return outList
end retConListFromItemNumList

on excludeTwoList(aList, bList)
  set aArray to NSArray’s arrayWithArray:(aList)
  
set bArray to NSArray’s arrayWithArray:(bList)
  
  
set aSet to NSMutableSet’s alloc()’s initWithArray:aArray
  
set bSet to NSMutableSet’s alloc()’s initWithArray:bArray
  
  
aSet’s minusSet:bSet –補集合
  
set resList to aSet’s allObjects() as list
  
  
return resList
end excludeTwoList

on getSequentialNumList(aMax)
  set outList to {}
  
repeat with i from 1 to aMax
    set the end of outList to i
  end repeat
  
return outList
end getSequentialNumList

★Click Here to Open This Script 

Posted in list | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy 10.15savvy NSArray NSMutableArray NSMutableSet | Leave a comment

リストの差分を取得して、登場順序が変わっていても1D List同士の登場要素が同じかをチェック

Posted on 5月 27, 2019 by Takaaki Naganoya

2つの1D List(1次元配列)同士の全要素をチェックし、登場順序に変更があったとしても要素自体に差がないかどうかをチェックするAppleScriptです。

……ソートしてから比較すれば、もっと短くて済むような気もしないでもないですが、もし違った場合には何が足りなくて(minusitems)、何が余計なのか(additems)をレポートしてくれるので実用的だと思います。

AppleScript名:リストの差分を取得して、登場順序が変わっていても1D List同士の登場要素が同じかをチェック
— Created 2019-05-27 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aList to {3, 2, 1, 7, 6, 4}
set bList to {1, 2, 3, 4, 6, 7}
set a1Res to checkAllItemsAreSame(aList, bList) of me
–> true (配列要素の登場順序が変わっていても要素はすべて同じ)

set aList to {3, 2, 1, 7, 6}
set bList to {1, 2, 3, 4, 6, 7}
set a2Res to checkAllItemsAreSame(aList, bList) of me
–> addItems:{4}, minusItems:{}}–配列要素に過不足があった

–1D List同士の全要素が(登場順序が変更になっていても)同じかどうかをチェック
on checkAllItemsAreSame(aList, bList)
  set dRes to getDiffBetweenLists(aList, bList) of me
  
set ddRes to (dRes is equal to {addItems:{}, minusItems:{}}) as boolean
  
if ddRes = true then
    return true
  else
    return dRes
  end if
end checkAllItemsAreSame

–1D List同士のdiffを検出
on getDiffBetweenLists(aArray as list, bArray as list)
  set allSet to current application’s NSMutableSet’s setWithArray:aArray
  
allSet’s addObjectsFromArray:bArray
  
  
–重複する要素のみ抜き出す
  
set duplicateSet to current application’s NSMutableSet’s setWithArray:aArray
  
duplicateSet’s intersectSet:(current application’s NSSet’s setWithArray:bArray)
  
  
–重複部分を削除する
  
allSet’s minusSet:duplicateSet
  
set resArray to (allSet’s allObjects()) as list
  
  
set aSet to current application’s NSMutableSet’s setWithArray:aArray
  
set bSet to current application’s NSMutableSet’s setWithArray:resArray
  
aSet’s intersectSet:bSet –積集合
  
set addRes to aSet’s allObjects() as list
  
  
set cSet to current application’s NSMutableSet’s setWithArray:bArray
  
cSet’s intersectSet:bSet –積集合
  
set minusRes to cSet’s allObjects() as list
  
  
return {addItems:minusRes, minusItems:addRes}
end getDiffBetweenLists

★Click Here to Open This Script 

Posted in list Record | Tagged 10.12savvy 10.13savvy 10.14savvy NSMutableSet NSSet | Leave a comment

Numbersで指定の2つの書類のデータのdiffを取る

Posted on 4月 19, 2019 by Takaaki Naganoya

指定の2つのNumbers書類(の中の現在表示中のシートのTable 1)同士のdiffを取るAppleScriptです。

# 書類内のシート内のどの表を処理するか、という階層化された対象選択を行うのにNSOutlineViewを用いたアラートダイアログを作っておきたい気持ちでいっぱいです

バージョン違いの書類間の差分を検出してレポートします。差分の評価は行単位で行なっており、同じデータでもカラムの順番を変えてあったりすると「別物」として検出します。

ただし、Numbersから2次元配列としてデータを抽出する際にすべてAppleScriptで処理するように書き換えた(macOS 10.14対策)ルーチンを使用しているので、大規模データの処理を行わせると(データ取得処理部分は)遅くなる可能性があります。

diffの計算部分はCocoaの機能に依存した(甘えまくった)処理を行なっているため、データが大きくてもそれほど遅くなりません。

612行の旧データと610行の新データをそれぞれ取得して差分を計算するのに、開発環境でだいたい3.5秒ぐらいです。同じ環境でBridgePlusを用いて1D List–> 2D List変換を行うバージョンを試してみたら、0.83秒ぐらいでした。

AppleScript名:Numbersで指定の2つの書類のデータのdiffを取る.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/04/19
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

tell application "Numbers"
  set dList to name of every document
  
set oldDoc to contents of first item of (choose from list dList with prompt "古いデータを選択してください")
  
set newDoc to contents of first item of (choose from list dList with prompt "新しいデータを選択してください")
end tell

set oldData to get2DListFromADoc(oldDoc) of me
set newData to get2DListFromADoc(newDoc) of me

–List同士のDiffを計算する
set dRes to getDiffBetweenLists(oldData, newData) of me
–> {addItems:{{"キャッツアイ恵庭", 42.87588548, 141.5834606, "北海道 恵庭市 住吉町 2-9-1"}}, minusItems:{{"セガワールド白河", 37.11931521, 140.1944139, "福島県 白河市 新高山 1-1 メガステージ白河内"}, {"プレイアイシー", 35.3721071, 139.272272, "神奈川県 秦野市 南矢名 1-15-1"}, {"駅前スタジアムIII", 33.8395736, 132.7521903, "愛媛県 松山市 大手町 2-4-1"}}}

on get2DListFromADoc(aDocName)
  tell application "Numbers"
    tell document aDocName
      tell active sheet
        set theTable to table 1
        
        
tell theTable
          set selection range to cell range
          
          
set hcCount to header column count
          
set hrCount to header row count
          
set frCount to footer row count
          
          
set cCount to column count
          
set rCount to row count
          
          
set outList to {}
          
          
repeat with i from (hrCount + 1) to rCount
            tell row i
              set tmpList to value of cells (hcCount + 1) thru cCount
              
set the end of outList to tmpList
            end tell
          end repeat
        end tell
        
        
return outList
        
      end tell
    end tell
  end tell
end get2DListFromADoc

on getDiffBetweenLists(aArray as list, bArray as list)
  set allSet to current application’s NSMutableSet’s setWithArray:aArray
  
allSet’s addObjectsFromArray:bArray
  
  
–重複する要素のみ抜き出す
  
set duplicateSet to current application’s NSMutableSet’s setWithArray:aArray
  
duplicateSet’s intersectSet:(current application’s NSSet’s setWithArray:bArray)
  
  
–重複部分を削除する
  
allSet’s minusSet:duplicateSet
  
set resArray to (allSet’s allObjects()) as list
  
  
set aSet to current application’s NSMutableSet’s setWithArray:aArray
  
set bSet to current application’s NSMutableSet’s setWithArray:resArray
  
aSet’s intersectSet:bSet –積集合
  
set addRes to aSet’s allObjects() as list
  
  
set cSet to current application’s NSMutableSet’s setWithArray:bArray
  
cSet’s intersectSet:bSet –積集合
  
set minusRes to cSet’s allObjects() as list
  
  
return {addItems:minusRes, minusItems:addRes}
end getDiffBetweenLists

★Click Here to Open This Script 

Posted in list | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSMutableSet NSSet Numbers | Leave a comment

CPU Family Nameを取得する

Posted on 12月 3, 2018 by Takaaki Naganoya

実行中のMacのMachine ID(MacBookPro10,1など)からIntel CPUのFamily Name(Ivy Bridgeなど)を取得するAppleScriptです。

Macの各モデルの搭載CPUについては、MacTrackerを参照しました。

MacTrackerのデータをコピー&ペーストでNumbers上に製品データを作成し(手動)、

ユニーク化(重複データの除去)処理を行なって(ASで処理)、プログラム上に展開しました(手動)。

実用性とか意味については、とくに考えていません。Machine IDとCPU Family Nameのデータについてはplistに記述してプログラム外部に追い出して独自でメンテナンスできるようにしたほうがよいと思われます。

AppleScript名:CPU Family Nameを取得する.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/12/03
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set macID to do shell script "sysctl -n hw.model" –get machine ID
–set macID to "MacBookPro99,1"–Error case

set myName to getIntelCoreProcessorFamilyName(macID) of me
—> "Ivy Bridge"

on getIntelCoreProcessorFamilyName(macID)
  –Machine ID & CPU Core Model Names (uniquefied)
  
set macList to {{"iMac4,1", "Yonah"}, {"iMac4,2", "Yonah"}, {"iMac5,2", "Merom"}, {"iMac5,1", "Merom"}, {"iMac6,1", "Merom"}, {"iMac7,1", "Merom"}, {"iMac8,1", "Penryn"}, {"iMac9,1", "Penryn"}, {"iMac10,1", "Wolfdale"}, {"iMac11,1", "Wolfdale, Lynnfield"}, {"iMac11,2", "Clarkdale"}, {"iMac11,3", "Clarkdale, Lynnfield"}, {"iMac12,1", "Sandy Bridge"}, {"iMac12,2", "Sandy Bridge"}, {"iMac13,1", "Ivy Bridge"}, {"iMac13,2", "Ivy Bridge"}, {"iMac14,1", "Haswell"}, {"iMac14,3", "Haswell"}, {"iMac14,2", "Haswell"}, {"iMac14,4", "Haswell"}, {"iMac15,1", "Haswell"}, {"iMac16,1", "Broadwell"}, {"iMac16,2", "Broadwell"}, {"iMac17,1", "Skylake"}, {"iMac18,1", "Kaby Lake"}, {"iMac18,2", "Kaby Lake"}, {"iMac18,3", "Kaby Lake"}, {"iMacPro1,1", "Skylake"}, {"Macmini1,1", "Yonah"}, {"Macmini2,1", "Merom"}, {"Macmini3,1", "Penryn"}, {"Macmini4,1", "Penryn"}, {"Macmini5,1", "Sandy Bridge"}, {"Macmini5,2", "Sandy Bridge"}, {"Macmini5,3", "Sandy Bridge"}, {"Macmini6,1", "Ivy Bridge"}, {"Macmini6,2", "Ivy Bridge"}, {"Macmini7,1", "Haswell"}, {"Macmini8,1", "Coffe Lake"}, {"MacPro1,1", "Woodcrest"}, {"MacPro2,1", "Clovertown"}, {"MacPro3,1", "Harpertown"}, {"MacPro4,1", "Bloomfield, Gainestown"}, {"MacPro5,1", "Bloomfield, Gulftown, Westmere"}, {"MacPro5,1", "Bloomfield, Westmere, Gulftown"}, {"MacPro6,1", "Ivy Bridge"}, {"MacBook1,1", "Yonah"}, {"MacBook2,1", "Merom"}, {"MacBook3,1", "Merom"}, {"MacBook4,1", "Penryn"}, {"MacBook5,1", "Penryn"}, {"MacBook5,2", "Penryn"}, {"MacBook6,1", "Penryn"}, {"MacBook7,1", "Penryn"}, {"MacBook8,1", "Broadwell"}, {"MacBook9,1", "Skylake"}, {"MacBook10,1", "Kaby Lake"}, {"MacBookAir1,1", "Merom"}, {"MacBookAir2,1", "Penryn"}, {"MacBookAir3,1", "Penryn"}, {"MacBookAir3,2", "Penryn"}, {"MacBookAir4,1", "Sandy Bridge"}, {"MacBookAir4,2", "Sandy Bridge"}, {"MacBookAir5,1", "Ivy Bridge"}, {"MacBookAir5,2", "Ivy Bridge"}, {"MacBookAir6,1", "Haswell"}, {"MacBookAir6,2", "Haswell"}, {"MacBookAir7,1", "Broadwell"}, {"MacBookAir7,2", "Broadwell"}, {"MacBookAir8,1", "Amber Lake Y"}, {"MacBookPro1,1", "Yonah"}, {"MacBookPro1,2", "Yonah"}, {"MacBookPro2,2", "Merom"}, {"MacBookPro2,1", "Merom"}, {"MacBookPro3,1", "Merom"}, {"MacBookPro4,1", "Penryn"}, {"MacBookPro5,1", "Penryn"}, {"MacBookPro5,2", "Penryn"}, {"MacBookPro5,5", "Penryn"}, {"MacBookPro5,4", "Penryn"}, {"MacBookPro5,3", "Penryn"}, {"MacBookPro7,1", "Penryn"}, {"MacBookPro6,2", "Arrandale"}, {"MacBookPro6,1", "Arrandale"}, {"MacBookPro8,1", "Sandy Bridge"}, {"MacBookPro8,2", "Sandy Bridge"}, {"MacBookPro8,3", "Sandy Bridge"}, {"MacBookPro9,2", "Ivy Bridge"}, {"MacBookPro9,1", "Ivy Bridge"}, {"MacBookPro10,1", "Ivy Bridge"}, {"MacBookPro10,2", "Ivy Bridge"}, {"MacBookPro11,1", "Haswell"}, {"MacBookPro11,2", "Haswell"}, {"MacBookPro11,3", "Haswell"}, {"MacBookPro12,1", "Broadwell"}, {"MacBookPro11,4", "Haswell"}, {"MacBookPro11,5", "Haswell"}, {"MacBookPro13,1", "Skylake"}, {"MacBookPro13,2", "Skylake"}, {"MacBookPro13,3", "Skylake"}, {"MacBookPro14,1", "Kaby Lake"}, {"MacBookPro14,2", "Kaby Lake"}, {"MacBookPro14,3", "Kaby Lake"}, {"MacBookPro15,2", "Coffee Lake"}, {"MacBookPro15,1", "Coffee Lake"}}
  
  
–2D List内の検索
  
set gList to searchInListByIndexItem(macList, 1, macID) of me
  
if gList = missing value or gList = {} then
    error "Error:" & macID & "is newer Machine than I expected in Dec 2018 or Older PowerPC Mac , may be"
  end if
  
  
set g2List to FlattenList(gList) of me –複数の結果が得られた場合に備える
  
return contents of second item of g2List
end getIntelCoreProcessorFamilyName

–2Dリストから、指定インデックスアイテムで、指定データが該当する最初のものを返す
on searchInListByIndexItem(aList as list, itemNum as integer, hitData as string)
  set setKey to current application’s NSMutableSet’s setWithArray:aList
  
  
if itemNum < 1 then return {}
  
set aPredicateStr to ("SELF[" & (itemNum – 1) as string) & "] == ’" & hitData & "’"
  
  
set aPredicate to current application’s NSPredicate’s predicateWithFormat:aPredicateStr
  
set aRes to (setKey’s filteredSetUsingPredicate:aPredicate)
  
set bRes to aRes’s allObjects()
  
  
set cRes to bRes as list of string or string –as anything
  
return cRes
end searchInListByIndexItem

–By Paul Berkowitz
–2009年1月27日 2:24:08:JST
–Re: Flattening Nested Lists
on FlattenList(aList)
  set oldDelims to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to {"????"}
  
set aString to aList as text
  
set aList to text items of aString
  
set AppleScript’s text item delimiters to oldDelims
  
return aList
end FlattenList

★Click Here to Open This Script 

Posted in shell script System | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSMutableSet NSPredicate | Leave a comment

Finder上で選択中のMarkdown書類をファイル名で昇順ソート(A→Z)して、各書類のタイトル見出しを取得する

Posted on 7月 8, 2018 by Takaaki Naganoya

Finder上で選択中のMarkdown書類を取得し、ファイル名で昇順ソート(A→Z)して、各Markdown書類中のタイトルのうち最もレベルの高い(重要な)ものを抽出し、まとめてテキストにしてクリップボードに転送するAppleScriptです。

大量にあるMarkdown書類の本文中から一番重要なタイトルを抽出する作業を……さすがに手作業で行うわけには行かなかったので、AppleScriptを書いて処理してみました。ただし、新規に書いた処理はほとんどなく、既存のルーチンの寄せ合わせで構成しています。

Finder上でMarkdown書類を選択した状態で本Scriptを実行すると(Markdown書類以外は除外して)、AppleScriptでMarkdown書類を読み込んで(Markdown書類がUTF-8固定なのでUTF-8を指定して読み込み)、正規表現で書類中のタイトルを抽出し、重要なタイトル(#の個数が少ない)をピックアップ。これをすべての書類について行います。

処理結果をクリップボードに転送します。

最終的には、(手作業で加工して)このようになります。

若干の手作業は発生してしまいますが、このScriptを組まなかったら、とてもその手作業を行う気も起こらなかったわけで、、、

AppleScript名:Finder上で選択中のMarkdown書類をファイル名で昇順ソート(A→Z)して、各書類のタイトル見出しを取得する
— Created 2018-06-26 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "Quartz"
use mdLib : script "Metadata Lib" version "1.0.0"
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html

property |NSURL| : a reference to current application’s |NSURL|
property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property SMSForder : a reference to current application’s SMSForder
property NSIndexSet : a reference to current application’s NSIndexSet
property NSPredicate : a reference to current application’s NSPredicate
property NSMutableSet : a reference to current application’s NSMutableSet
property NSFileManager : a reference to current application’s NSFileManager
property NSCountedSet : a reference to current application’s NSCountedSet
property NSURLPathKey : a reference to current application’s NSURLPathKey
property NSMutableArray : a reference to current application’s NSMutableArray
property NSURLNameKey : a reference to current application’s NSURLNameKey
property NSSortDescriptor : a reference to current application’s NSSortDescriptor
property NSURLIsPackageKey : a reference to current application’s NSURLIsPackageKey
property NSRegularExpression : a reference to current application’s NSRegularExpression
property NSURLIsDirectoryKey : a reference to current application’s NSURLIsDirectoryKey
property NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey
property NSURLContentModificationDateKey : a reference to current application’s NSURLContentModificationDateKey
property NSRegularExpressionAnchorsMatchLines : a reference to current application’s NSRegularExpressionAnchorsMatchLines
property NSDirectoryEnumerationSkipsHiddenFiles : a reference to current application’s NSDirectoryEnumerationSkipsHiddenFiles
property NSRegularExpressionDotMatchesLineSeparators : a reference to current application’s NSRegularExpressionDotMatchesLineSeparators

load framework

–set inFiles to (choose file of type {"pdf"} with prompt "Choose your PDF files:" with multiple selections allowed)
tell application "Finder"
  set inFiles to selection as alias list
end tell

if inFiles = {} then return

–指定のAlias listのうちMarkdown書類のみ抽出
set filRes1 to filterAliasListByUTI(inFiles, "net.daringfireball.markdown") of me

–指定のPOSIX path listから、各Markdown書類中の一番重要な見出しを抽出して返す
set tRes to listTitlesFromMarkdownDocPathList(filRes1) of me

–取得したタイトル一覧リストをテキストに変換
set t2Res to retStrFromArrayWithDelimiter(tRes, return) of me

–クリップボードに結果を転送
set the clipboard to t2Res

on listTitlesFromMarkdownDocPathList(inFiles)
  set outList to {}
  
set inFilesSorted to my filesInListSortAscending(inFiles)
  
  
repeat with i in inFilesSorted
    –POSIX pathからaliasにパス変換してテキスト読み込み
    
set j to POSIX file (contents of i)
    
set jj to j as alias
    
set aStr to (read jj as «class utf8»)
    
    
set aList to retHeaders(aStr) of me –Markdown書類中の見出しをリストアップ
    
–>  {​​​​​{​​​​​​​1, ​​​​​​​" 2008/3/9 5桁の乱数を生成"​​​​​}​​​}
    
    
if aList is not equal to {} then
      –2D Listの昇順ソート
      
set sortIndexes to {0} –Key Item id: begin from 0
      
set sortOrders to {true} –ascending = true
      
set sortTypes to {"compare:"}
      
set resList to (current application’s SMSForder’s subarraysIn:(aList) sortedByIndexes:sortIndexes ascending:sortOrders sortTypes:sortTypes |error|:(missing value)) as list
      
      
set aCon to contents of second item of first item of resList
      
set the end of outList to aCon
    end if
  end repeat
  
return outList
end listTitlesFromMarkdownDocPathList

on filesInListSortAscending(aliasList as list)
  set cList to {}
  
repeat with i in aliasList
    set j to contents of i
    
set aFileName to ((current application’s NSString’s stringWithString:j)’s valueForKeyPath:"lastPathComponent")
    
set the end of cList to {fileName:aFileName, pathDat:j}
  end repeat
  
  
set aResList to sortRecListByLabel(cList, "fileName", true) of me –昇順ソート
  
set bResList to (aResList’s valueForKeyPath:"pathDat") as list of string or string
  
return bResList
end filesInListSortAscending

–Alias listから指定UTIに含まれるものをPOSIX pathのリストで返す
on filterAliasListByUTI(aList, targUTI)
  set newList to {}
  
repeat with i in aList
    set j to POSIX path of i
    
set tmpUTI to my retUTIfromPath(j)
    
set utiRes to my filterUTIList({tmpUTI}, targUTI)
    
if utiRes is not equal to {} then
      set the end of newList to j
    end if
  end repeat
  
return newList
end filterAliasListByUTI

–指定のPOSIX pathのファイルのUTIを求める
on retUTIfromPath(aPOSIXPath)
  set aURL to |NSURL|’s fileURLWithPath:aPOSIXPath
  
set {theResult, theValue} to aURL’s getResourceValue:(reference) forKey:NSURLTypeIdentifierKey |error|:(missing value)
  
  
if theResult = true then
    return theValue as string
  else
    return theResult
  end if
end retUTIfromPath

–UTIリストが指定UTIに含まれているかどうか演算を行う
on filterUTIList(aUTIList, aUTIstr)
  set anArray to NSArray’s arrayWithArray:aUTIList
  
set aPred to NSPredicate’s predicateWithFormat_("SELF UTI-CONFORMS-TO %@", aUTIstr)
  
set bRes to (anArray’s filteredArrayUsingPredicate:aPred) as list
  
return bRes
end filterUTIList

on returnNumberCharsOnly(aStr)
  set anNSString to current application’s NSString’s stringWithString:aStr
  
set anNSString to anNSString’s stringByReplacingOccurrencesOfString:"[^0-9]" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, anNSString’s |length|()}
  
return anNSString as text
end returnNumberCharsOnly

–リストに入れたレコードを、指定の属性ラベルの値でソート
on sortRecListByLabel(aRecList as list, aLabelStr as string, ascendF as boolean)
  set aArray to current application’s NSArray’s arrayWithArray:aRecList
  
  
set sortDesc to current application’s NSSortDescriptor’s alloc()’s initWithKey:aLabelStr ascending:ascendF
  
set sortDescArray to current application’s NSArray’s arrayWithObjects:sortDesc
  
set sortedArray to aArray’s sortedArrayUsingDescriptors:sortDescArray
  
return sortedArray
end sortRecListByLabel

–見出し抽出用サブルーチン群
on retHeaders(aCon)
  set tList to {}
  
set regStr to "^#{1,6}[^#]*?$"
  
  
set headerList to my findPattern:regStr inString:aCon
  
repeat with i in headerList
    set j to contents of i
    
set regStr2 to "^#{1,6}[^#]*?"
    
set headerLevel to length of first item of (my findPattern:regStr2 inString:j)
    
set the end of tList to {headerLevel, text (headerLevel + 1) thru -1 in j}
  end repeat
  
  
return tList
end retHeaders

on findPattern:thePattern inString:theString
  set theOptions to ((NSRegularExpressionDotMatchesLineSeparators) as integer) + ((NSRegularExpressionAnchorsMatchLines) as integer)
  
set theRegEx to NSRegularExpression’s regularExpressionWithPattern:thePattern options:theOptions |error|:(missing value)
  
set theFinds to theRegEx’s matchesInString:theString options:0 range:{location:0, |length|:length of theString}
  
set theFinds to theFinds as list — so we can loop through
  
set theResult to {} — we will add to this
  
set theNSString to NSString’s stringWithString:theString
  
repeat with i from 1 to count of items of theFinds
    set theRange to (item i of theFinds)’s range()
    
set end of theResult to (theNSString’s substringWithRange:theRange) as string
  end repeat
  
return theResult
end findPattern:inString:

–リストを指定デリミタをはさんでテキスト化
on retStrFromArrayWithDelimiter(aList, aDelim)
  set anArray to current application’s NSArray’s arrayWithArray:aList
  
set aRes to anArray’s componentsJoinedByString:aDelim
  
return aRes as list of string or string
end retStrFromArrayWithDelimiter

★Click Here to Open This Script 

Posted in file list Markdown regexp Sort Text | Tagged 10.11savvy 10.12savvy 10.13savvy Finder NSArray NSCountedSet NSDirectoryEnumerationSkipsHiddenFiles NSFileManager NSIndexSet NSMutableArray NSMutableSet NSPredicate NSRegularExpression NSRegularExpressionAnchorsMatchLines NSRegularExpressionDotMatchesLineSeparators NSSortDescriptor NSString NSURL NSURLContentModificationDateKey NSURLIsDirectoryKey NSURLIsPackageKey NSURLNameKey NSURLPathKey NSURLTypeIdentifierKey | 3 Comments

電子書籍(PDF)をオンラインストアで販売中!

Google Search

Popular posts

  • macOS 13, Ventura(継続更新)
  • アラートダイアログ上にWebViewで3Dコンテンツを表示(WebGL+three.js)v3
  • UI Browserがgithub上でソース公開され、オープンソースに
  • macOS 13 TTS Voice環境に変更
  • Xcode 14.2でAppleScript App Templateを復活させる
  • 2022年に書いた価値あるAppleScript
  • ChatGPTで文章のベクトル化(Embedding)
  • 新発売:AppleScriptからSiriを呼び出そう!
  • iWork 12.2がリリースされた
  • 従来と異なるmacOS 13の性格?
  • 新発売:CotEditor Scripting Book with AppleScript
  • macOS 13対応アップデート:AppleScript実践的テクニック集(1)GUI Scripting
  • AS関連データの取り扱いを容易にする(はずの)privateDataTypeLib
  • macOS 13でNSNotFoundバグふたたび
  • macOS 12.5.1、11.6.8でFinderのselectionでスクリーンショット画像をopenできない問題
  • ChatGPTでchatに対する応答文を取得
  • 新発売:iWork Scripting Book with AppleScript
  • Finderの隠し命令openVirtualLocationが発見される
  • macOS 13.1アップデートでスクリプトエディタの挙動がようやくまともに
  • あのコン過去ログビューワー(暫定版)

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1390) 10.14savvy (586) 10.15savvy (434) 11.0savvy (277) 12.0savvy (185) 13.0savvy (55) CotEditor (60) Finder (47) iTunes (19) Keynote (98) NSAlert (60) NSArray (51) NSBezierPath (18) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (18) NSImage (41) NSJSONSerialization (21) NSMutableArray (62) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (117) NSURL (97) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (56) Pages (37) Safari (41) Script Editor (20) WKUserContentController (21) WKUserScript (20) WKUserScriptInjectionTimeAtDocumentEnd (18) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • Clipboard
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • drive
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • rectangle
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2023年9月
  • 2023年8月
  • 2023年7月
  • 2023年6月
  • 2023年5月
  • 2023年4月
  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC