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

タグ: NSRegularExpressionSearch

クリップボード内の文字種別を集計して円グラフ表示

Posted on 5月 16, 2020 by Takaaki Naganoya

クリップボード内に文字列が入っていれば、いいかえれば「文字列をコピーした状態であれば」、クリップボード内容をテキストとして取り出して文字種別ごとに集計して構成比を円グラフで表示するAppleScriptです。

# CAUTION: This script process Japanese characters. So, this script make no sense for other language users

グラフ表示部分は手抜きでGoogle Chartsを呼び出しているだけなので、Macがネットワークに接続されていない場合には表示できません。

macOS標準装備のScript Menuに入れて使っています。複数の円グラフを表示させることも可能なので、典型的な例文(新聞、論文、なろう系、技術系文章、文学作品)のグラフを一覧表示して、どの例文の使用比率に近いかといったことを見てわかるようにできそうです(やらないけど)。

ありものをただ引っ張り出してきて、Script文でつないだだけなので、オリジナルで記述した部分はほとんどありません。

とはいえ、技術的にはいろいろなハードルを乗り越えまくって動かしているものでもあります。

・メインスレッドでしか動かせないWkWebView、NSAlertをScriptから呼び出している(実行環境に左右されずに実行)
・Cocoa Scriptingを行うAppleScriptObjCをscript文でscript object化して(カプセル化して)呼び出し、再利用
・WkWebViewをdialog内に表示して、マウスオーバーでデータ内容が見えるようなインタラクティブなグラフを表示

といった、いろいろ無茶なことをやっているScriptです。ただ、すでに見慣れた光景になりつつありますけれども。

AppleScript名:クリップボード内の文字種別を集計して円グラフ表示.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/05/14
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use framework "WebKit"
use scripting additions

property |NSURL| : a reference to current application’s |NSURL|
property NSAlert : a reference to current application’s NSAlert
property NSString : a reference to current application’s NSString
property NSButton : a reference to current application’s NSButton
property WKWebView : a reference to current application’s WKWebView
property WKUserScript : a reference to current application’s WKUserScript
property NSURLRequest : a reference to current application’s NSURLRequest
property NSRunningApplication : a reference to current application’s NSRunningApplication
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding
property WKUserContentController : a reference to current application’s WKUserContentController
property WKWebViewConfiguration : a reference to current application’s WKWebViewConfiguration
property NSScreenSaverWindowLevel : a reference to current application’s NSScreenSaverWindowLevel
property WKUserScriptInjectionTimeAtDocumentEnd : a reference to current application’s WKUserScriptInjectionTimeAtDocumentEnd

property returnCode : 0

–Calc Clipboard
set aRes to clipAnaliticsMain() of clipboardInfoKit
if aRes = false then return —クリップボードが空だった(文字列的に)

set totalC to totalC of aRes

set aList to {{"文字種別", "構成比"}} & rating of aRes

set aJsonArrayStr to array2DToJSONArray(aList) of me

–Pie Chart Template HTML
set myStr to "<!DOCTYPE html>
<html lang=\"UTF-8\">
<body>
<div id=\"piechart\"></div>

<script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>

<script type=\"text/javascript\">
// Load google charts
google.charts.load(’current’, {’packages’:[’corechart’]});
google.charts.setOnLoadCallback(drawChart);

// Draw the chart and set the chart values
function drawChart() {
var data = google.visualization.arrayToDataTable(%@);

// Optional; add a title and set the width and height of the chart
var options = {
is3D: true,
   ’width’:600, ’height’:400
};

// Display the chart inside the <div> element with id=\"piechart\"
var chart = new google.visualization.PieChart(document.getElementById(’piechart’));
chart.draw(data, options);
}
</script>

</body>
</html>"

set aString to current application’s NSString’s stringWithFormat_(myStr, aJsonArrayStr) as string

set paramObj to {myMessage:"文字種別構成比", mySubMessage:"クリップボードの内容を集計。文字数は" & (totalC as string) & "文字", htmlStr:aString}
–my browseStrWebContents:paramObj–for debug
my performSelectorOnMainThread:"browseStrWebContents:" withObject:(paramObj) waitUntilDone:true

on browseStrWebContents:paramObj
  set aMainMes to myMessage of paramObj
  
set aSubMes to mySubMessage of paramObj
  
set htmlString to (htmlStr of paramObj)
  
  
set aWidth to 600
  
set aHeight to 450
  
  
–WebViewをつくる
  
set aConf to WKWebViewConfiguration’s alloc()’s init()
  
  
–指定HTML内のJavaScriptをFetch
  
set jsSource to pickUpFromToStr(htmlString, "<script type=\"text/javascript\">", "</script>") of me
  
  
set userScript to WKUserScript’s alloc()’s initWithSource:jsSource injectionTime:(WKUserScriptInjectionTimeAtDocumentEnd) forMainFrameOnly:true
  
set userContentController to WKUserContentController’s alloc()’s init()
  
userContentController’s addUserScript:(userScript)
  
aConf’s setUserContentController:userContentController
  
  
set aWebView to WKWebView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, aWidth, aHeight – 100)) configuration:aConf
  
aWebView’s setNavigationDelegate:me
  
aWebView’s setUIDelegate:me
  
aWebView’s setTranslatesAutoresizingMaskIntoConstraints:true
  
  
set bURL to |NSURL|’s fileURLWithPath:(POSIX path of (path to me))
  
aWebView’s loadHTMLString:htmlString baseURL:(bURL)
  
  
— set up alert  
  
set theAlert to NSAlert’s alloc()’s init()
  
tell theAlert
    its setMessageText:aMainMes
    
its setInformativeText:aSubMes
    
its addButtonWithTitle:"OK"
    
–its addButtonWithTitle:"Cancel"
    
its setAccessoryView:aWebView
    
    
set myWindow to its |window|
  end tell
  
  
myWindow’s setLevel:(NSScreenSaverWindowLevel)
  
  
— show alert in modal loop
  
NSRunningApplication’s currentApplication()’s activateWithOptions:0
  
my performSelectorOnMainThread:"doModal:" withObject:(theAlert) waitUntilDone:true
  
  
–Stop Web View Action
  
set bURL to |NSURL|’s URLWithString:"about:blank"
  
set bReq to NSURLRequest’s requestWithURL:bURL
  
aWebView’s loadRequest:bReq
  
  
if (my returnCode as number) = 1001 then error number -128
end browseStrWebContents:

on doModal:aParam
  set (my returnCode) to (aParam’s runModal()) as number
end doModal:

on viewDidLoad:aNotification
  return true
end viewDidLoad:

on fetchJSSourceString(aURL)
  set jsURL to |NSURL|’s URLWithString:aURL
  
set jsSourceString to NSString’s stringWithContentsOfURL:jsURL encoding:(NSUTF8StringEncoding) |error|:(missing value)
  
return jsSourceString
end fetchJSSourceString

on pickUpFromToStr(aStr as string, s1Str as string, s2Str as string)
  set a1Offset to offset of s1Str in aStr
  
if a1Offset = 0 then return false
  
set bStr to text (a1Offset + (length of s1Str)) thru -1 of aStr
  
set a2Offset to offset of s2Str in bStr
  
if a2Offset = 0 then return false
  
set cStr to text 1 thru (a2Offset – (length of s2Str)) of bStr
  
return cStr as string
end pickUpFromToStr

–リストを任意のデリミタ付きでテキストに
on retArrowText(aList, aDelim)
  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 retArrowText

on array2DToJSONArray(aList)
  set anArray to current application’s NSMutableArray’s arrayWithArray:aList
  
set jsonData to current application’s NSJSONSerialization’s dataWithJSONObject:anArray options:(0 as integer) |error|:(missing value) –0 is
  
set resString to current application’s NSString’s alloc()’s initWithData:jsonData encoding:(current application’s NSUTF8StringEncoding)
  
return resString
end array2DToJSONArray

script clipboardInfoKit
  use scripting additions
  
use framework "Foundation"
  
property parent : AppleScript
  
  
property NSString : a reference to current application’s NSString
  
property NSNumber : a reference to current application’s NSNumber
  
property NSDictionary : a reference to current application’s NSDictionary
  
property NSCountedSet : a reference to current application’s NSCountedSet
  
property NSCharacterSet : a reference to current application’s NSCharacterSet
  
property NSMutableArray : a reference to current application’s NSMutableArray
  
property NSNumberFormatter : a reference to current application’s NSNumberFormatter
  
property NSRegularExpressionSearch : a reference to current application’s NSRegularExpressionSearch
  
property NSNumberFormatterRoundUp : a reference to current application’s NSNumberFormatterRoundUp
  
property NSNumberFormatterRoundDown : a reference to current application’s NSNumberFormatterRoundDown
  
  
  
on clipAnaliticsMain()
    set cCount to 0
    
set hCount to 0
    
set kCount to 0
    
set oCount to 0
    
set tCount to 0
    
    
using terms from scripting additions
      set aStr to (the clipboard as «class utf8»)
      
if aStr = "" then
        display dialog "No text data in clipboard" buttons {"OK"} default button 1
        
return false
      end if
    end using terms from
    
    
set aRec to detectCharKindRating(aStr) of me
    
    
set cCount to cCount + (kanjiNum of aRec)
    
set hCount to hCount + (hiraganaNum of aRec)
    
set kCount to kCount + (katakanaNum of aRec)
    
set oCount to oCount + (otherNum of aRec)
    
set tCount to tCount + (totalCount of aRec)
    
    
return {rating:{{"漢字", cCount}, {"ひらがな", hCount}, {"カタカナ", kCount}, {"その他", oCount}}, totalC:tCount}
  end clipAnaliticsMain
  
  
  
  
on detectCharKindRating(aStr as string)
    set aList to NSMutableArray’s arrayWithArray:(characters of aStr)
    
set theCountedSet to NSCountedSet’s alloc()’s initWithArray:aList
    
set theEnumerator to theCountedSet’s objectEnumerator()
    
    
set cCount to 0
    
set hCount to 0
    
set kCount to 0
    
set oCount to 0
    
set totalC to length of aStr
    
    
repeat
      set aValue to theEnumerator’s nextObject()
      
if aValue is missing value then exit repeat
      
      
set aStr to aValue as string
      
set tmpCount to (theCountedSet’s countForObject:aValue)
      
      
set s1Res to chkKanji(aStr) of me
      
set s2Res to chkKatakana(aStr) of me
      
set s3Res to chkHiragana(aStr) of me
      
      
if s1Res = true then
        set cCount to cCount + tmpCount
      else if s2Res = true then
        set kCount to kCount + tmpCount
      else if s3Res = true then
        set hCount to hCount + tmpCount
      else
        set oCount to oCount + tmpCount
      end if
    end repeat
    
    
set ckRes to roundingUp((cCount / totalC) * 100, 1) of me
    
set kkRes to roundingUp((kCount / totalC) * 100, 1) of me
    
set hgRes to roundingUp((hCount / totalC) * 100, 1) of me
    
set otRes to roundingUp((oCount / totalC) * 100, 1) of me
    
    
return {kanjiNum:cCount, kanjiRating:ckRes, hiraganaNum:hCount, hiraganaRating:hgRes, katakanaNum:kCount, katakanaRating:kkRes, otherNum:oCount, otherRating:otRes, totalCount:totalC}
  end detectCharKindRating
  
  
  
on chkKanji(aChar)
    return detectCharKind(aChar, "[一-龠]") of me
  end chkKanji
  
  
on chkHiragana(aChar)
    return detectCharKind(aChar, "[ぁ-ん]") of me
  end chkHiragana
  
  
on chkKatakana(aChar)
    return detectCharKind(aChar, "[ァ-ヶ]") of me
  end chkKatakana
  
  
on detectCharKind(aChar, aPattern)
    set aChar to NSString’s stringWithString:aChar
    
set searchStr to NSString’s stringWithString:aPattern
    
set matchRes to aChar’s rangeOfString:searchStr options:(NSRegularExpressionSearch)
    
if matchRes’s location() = (current application’s NSNotFound) or (matchRes’s location() as number) > 9.99999999E+8 then
      return false
    else
      return true
    end if
  end detectCharKind
  
  
on roundingUp(aNum, aDigit as integer)
    set a to aNum as real
    
set aFormatter to NSNumberFormatter’s alloc()’s init()
    
aFormatter’s setMaximumFractionDigits:aDigit
    
aFormatter’s setRoundingMode:(NSNumberFormatterRoundUp)
    
set aStr to aFormatter’s stringFromNumber:(NSNumber’s numberWithFloat:a)
    
return (aStr as text) as real
  end roundingUp
end script

★Click Here to Open This Script 

Posted in dialog Internet JavaScript Text | Tagged 10.13savvy 10.14savvy 10.15savvy NSAlert NSButton NSCharacterSet NSCountedSet NSDictionary NSMutableArray NSNumber NSNumberFormatter NSNumberFormatterRoundDown NSNumberFormatterRoundUp NSRegularExpressionSearch NSRunningApplication NSScreenSaverWindowLevel NSString NSURL NSURLRequest NSUTF8StringEncoding WKUserContentController WKUserScript WKUserScriptInjectionTimeAtDocumentEnd WKWebView WKWebViewConfiguration | Leave a comment

指定フォルダ以下のすべてのファイルとフォルダ名から絵文字を除去する v2

Posted on 11月 5, 2019 by Takaaki Naganoya

指定フォルダ以下のすべてのファイル名とフォルダ名から絵文字を除去するAppleScriptです。Shane StanleyのremoveEmojiルーチンを使っています。

macOS 10.14.1で絵文字が大幅に追加されたため、これらの絵文字をファイル名に用いていた場合には10.14.1以下のバージョンのOS環境にそのままファイルを持っていくことができません。

 Zipアーカイブ → 展開時にエラー
 DiskImageにコピーするファイルを格納し、古いOSに持って行ってドライブとしてマウントしてファイルコピー → コピーできない(エラー)

という状態になります。絵文字自体に害はないのですが、規格がコロコロ変わる(追加される)ことで、ファイル名に用いるのには問題があるということでしょう。


▲もともとのファイル名、フォルダ名。絵文字を大量に使用している(普段はファイル名に絵文字は使っていません)


▲本Scriptで一括で処理したファイル名、フォルダ名。害のない1️⃣2️⃣3️⃣などの文字だけは残る

実際に作ってみたら、aliasに対するリネームはしょっちゅう行ってきたものの、POSIX pathを用いて指定フォルダ以下すべてをリネームするようなScriptは組んでいなかったので、ちょっと考えさせられました。


▲本Scriptでリネームして、CotEditorのScript PackをmacOS 10.13.6の環境に持っていけました。ただ、絵文字がないと寂しい感じがします

指定フォルダ以下のファイル/フォルダを一括取得するのに、今回はあえてSpotlightを使っていません。ファイルサーバー上のファイル/フォルダを処理する可能性がありそうなのと、外部ライブラリを使わないほうがよいと考え、このような構成になっています。

AppleScript名:指定フォルダ以下のすべてのファイルとフォルダ名から絵文字を除去する v2.scptd
—
—  Created by: Takaaki Naganoya
—  Created on: 2019/11/04
—
—  Copyright © 2019 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property |NSURL| : a reference to current application’s |NSURL|
property NSString : a reference to current application’s NSString
property NSPredicate : a reference to current application’s NSPredicate
property NSFileManager : a reference to current application’s NSFileManager
property NSMutableArray : a reference to current application’s NSMutableArray
property NSRegularExpressionSearch : a reference to current application’s NSRegularExpressionSearch
property NSURLBookmarkResolutionWithoutUI : a reference to current application’s NSURLBookmarkResolutionWithoutUI

set aFol to POSIX path of (choose folder)

set anArray to NSMutableArray’s array()
set erArray to NSMutableArray’s array()
set aPath to NSString’s stringWithString:aFol
set dirEnum to NSFileManager’s defaultManager()’s enumeratorAtPath:aPath

repeat
  set aName to (dirEnum’s nextObject())
  
if aName = missing value then exit repeat
  
set aFullPath to aPath’s stringByAppendingPathComponent:aName
  
  
anArray’s addObject:aFullPath
end repeat

—逆順に(フォルダの深い場所&ファイル名から先に処理)
set revArray to (anArray’s reverseObjectEnumerator()’s allObjects()) as list

—リネーム
repeat with i in revArray
  set j to (NSString’s stringWithString:(contents of i))
  
set curName to j’s lastPathComponent() as string
  
set newName to removeEmoji(curName) of me
  
  
if curName is not equal to newName then
    set fRes to renameFileItem(j as string, newName) of me
    
if fRes = false then
      (erArray’s addObject:{j, newName})
    end if
  end if
end repeat

return erArray as list —リネームできなかったパス(フルパス、リネームするはずだった名称)

—絵文字除去
on removeEmoji(aStr)
  set aNSString to NSString’s stringWithString:aStr
  
return (aNSString’s stringByReplacingOccurrencesOfString:"[\\U0001F600-\\U0001F64F\\U0001F300-\\U0001F5FF\\U0001F680-\\U0001F6FF\\U00002600-\\U000026FF\\U00002700-\\U000027BF\\U0000FE00-\\U0000fE0F\\U0001F900-\\U0001F9FF\\U0001F1E6-\\U0001F1FF\\U00002B50-\\U00002B50\\U0000231A-\\U0000231B\\U00002328-\\U000023FA\\U000024C2-\\U000024C2\\U0001F194-\\U0001F194\\U0001F170-\\U0001F251\\U000025AB-\\U000025FE\\U00003297-\\U00003299\\U00002B55-\\U00002B55\\U00002139-\\U00002139\\U00002B1B-\\U00002B1C\\U000025AA-\\U000025AA\\U0001F004-\\U0001F004\\U0001F0CF-\\U0001F0CF]" withString:"" options:(NSRegularExpressionSearch) range:{0, aNSString’s |length|()}) as text
end removeEmoji

—ファイル/フォルダのリネーム
on renameFileItem(aPOSIXPath, newName)
  set theNSFileManager to NSFileManager’s defaultManager()
  
set POSIXPathNSString to NSString’s stringWithString:(aPOSIXPath)
  
  
–Make New File Path
  
set anExtension to POSIXPathNSString’s pathExtension()
  
set newPath to (POSIXPathNSString’s stringByDeletingLastPathComponent()’s stringByAppendingPathComponent:newName) –’s stringByAppendingPathExtension:anExtension
  
  
–Rename
  
if theNSFileManager’s fileExistsAtPath:newPath then
    return true
  else
    set theResult to theNSFileManager’s moveItemAtPath:POSIXPathNSString toPath:newPath |error|:(missing value)
    
if (theResult as integer = 1) then
      return (newPath as string)
    else
      return false
    end if
  end if
end renameFileItem

★Click Here to Open This Script 

Posted in file File path regexp Text | Tagged 10.14savvy 10.15savvy NSFileManager NSMutableArray NSPredicate NSRegularExpressionSearch NSString NSURL | Leave a comment

文字列から絵文字を削除

Posted on 11月 4, 2019 by Takaaki Naganoya

Shane Stanleyから投稿してもらった(いただいた)実用レベルの絵文字削除ルーチンです。

いろんな方面からツッコミが入って、徐々に実用レベルに到達するのではないかと予想していた絵文字削除ルーチン、いきなり最終兵器的なルーチンの登場により、「これでいいでしょ?」と思えるレベルに到達しました。

AppleScript名:remove emoji v0
—
—  Created by: Shane Stanley
—  Created on: 2019/11/04
—
use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use scripting additions

removeEmoji("2203)🔄❎⚙️🇯🇵簡易日本語形態素解析📚してそれっぽく❌伏せ字に(□に置き換え).scptd") of me
–> "2203)簡易日本語形態素解析してそれっぽく伏せ字に(□に置き換え).scptd"

on removeEmoji(aStr)
  set aNSString to current application’s NSString’s stringWithString:aStr
  
— Emoticons, Misc Symbols and Pictographs, Transport and Map, Misc symbols, Dingbats, Variation Selectors, Supplemental Symbols and Pictographs, Flags
  
return (aNSString’s stringByReplacingOccurrencesOfString:"[\\U0001F600-\\U0001F64F\\U0001F300-\\U0001F5FF\\U0001F680-\\U0001F6FF\\U00002600-\\U000026FF\\U00002700-\\U000027BF\\U0000FE00-\\U0000fE0F\\U0001F900-\\U0001F9FF\\U0001F1E6-\\U0001F1FF]" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, aNSString’s |length|()}) as text
end removeEmoji

★Click Here to Open This Script 

ただ、そこは一応「すべての絵文字」を入力して試しておく必要を感じるところ。手作業でぽちぽちキーボードから(絵文字バレットから)絵文字を入力しまくって本ルーチンで処理してみたところ、どうも文字コード上の「飛び地」にあるとおぼしき絵文字が消えません。

なので、削除テーブル部分に「消えなかった絵文字のコード」をこれでもかと追加しまくり、削除対象文字テーブルを強化してみました。一部、対象文字よりもひろめに削除範囲が指定されている箇所もありますが、本ルーチンは主にファイル名に対して使用された絵文字を除去してファイルの後方互換性を確保すること(最新のOSよりも古いバージョンのOSとファイルを安全に交換すること)が目的なので、そんなマイナー記号類が削除されても気にしないことにします。

すべての絵文字が削除されたわけではないといいますか、絵文字っぽい文字でなくなっただけで残っていたりもするのですが、今度はこれらの文字を消すと実害もありそうなので、現状ではこのぐらいでよいかと思われます。

もちろん、すぐにCotEditorのメニューに突っ込んで、選択範囲の絵文字を削除できるようにしておきました。

AppleScript名:remove emoji.scptd
—
—  Created by: Shane Stanley
—  Created on: 2019/11/04
—  Modified by: Takaaki Naganoya (Emoji Table Data)

use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use scripting additions

set allEmoji to "☺️☹️☠️✌️☝️🖐✍️1️⃣2️⃣3️⃣⚙️😀😃😄😁😆😅😂🤣☺️😊😇🙂🙃😉😌😍🥰😘😗😙😚😋😛😝😜🤪🤨🧐🤓😎🤩🥳😏😒😞😔😟😕🙁☹️😣😖😫😩🥺😢😭😤😡🤬🤯😳🥵🥶😱😨😨😰😥😓🤗🤔🤭🤫🤥😶😐😑😬🙄😯😦😧😮😲😴🤤😪😵🤐🥴🤢🤮🤧😷🤒🤕🤑🤠😈👿👹👺🤡💩👻💀☠️👽👾🤖🎃😺😸😹😻😼😽🙀😿😾🤲👐🙌👏🤝👍👎👊✊🤛🤜🤞✌️🤟🤘👌👈👉👆👇☝️✋🤚🖐🖖👋🤙💪🖕✍️🙏🦶🦵🐶🐱🐭🐰🦊🐻🐼🐨🐯🦁🐮🐷🐽🐸🐵🙈🙉🙊🐒🐔🐧🐦🐤🐣🐥🦆🦅🦉🦇🐗🐴🦄🐝🐛🦋🐌🐞🐜🦟🦗🕷🕸🦂🐍🦎🦖🐙🦑🦐🦞🦀🐡🐟🐬🐳🦈🐊🐅🐆🦓🦍🐘🦛🦏🐪🐫🦘🐃🐂🐄🐎🐏🐑🦙🐐🦌🐕🐩🐈🐓🦃🦚🦜🦢🕊🐇🦝🦡🐁🐀🐿🐲🌵🎄🌲🌳🌴🌱🌿🍀🍃🍂🍁🍄🌾🌹🥀🌺🌼🌻🌚🌕🌖🌗🌘🌒🌎💫⭐️🌟⚡️☄️💥🔥🌪🌈🌤⛅️🌥☁️🌦🌧⛈🌩❄️☃️🌬💨💧💦☔️🌫🍏🍎🍐🍊🍋🍌🍇🍓🍈🍒🍑🍍🥥🥝🍅🍆🥑🌶🌽🥕🥔🍠🥐🥯🍞🥖🥨🧀🥚🍳🥞🥓🥩🍗🍖🦴🦴🌭🍕🥪🥙🌮🌯🥗🥘🥫🍝🍜🍛🍣🍱🍤🍙🍚🍘🍥🥠🥮🍢🍦🍰🎂🍭🍬🍫🍿🍩🍪🌰🥜🍯🥛🍼☕️🍵🥤🍶🍺🍻🥂🍷🥃🍸🍹🍾🥄🍴🍽🥣🥡🥢🧂🏀⚾️🥎🎾🏐🏉🥏🎱🏓🏸🏒🏏⛳️🏹🎣🥊🥋🎽🛹🛷⛸🥌🎿⛷🏂🏋️‍♂️🤼‍♀️🤼‍♂️🤺🤾‍♀️🤾‍♂️🏌️‍♀️🏌️‍♂️🏇🧘‍♀️🧘‍♂️🏄‍♀️🏄‍♂️🏊‍♀️🏊‍♂️🤽‍♀️🤽‍♂️🚣‍♀️🚣‍♂️🧗‍♀️🧗‍♂️🚵‍♀️🚵‍♂️🚴‍♀️🚴‍♂️🏆🥇🥈🥉🏅🎖🏵🎗🎫🎟🎪🤹‍♀️🤹‍♂️🎭🎨🎬🎤🎧🎼🎹🥁🎷🎺🎸🎻🎲♟🎯🎳🎮🎰🧩🚗🚙🚌🚎🏎🚓🚑🚒🚐🚛🚜🛴🚲🏍🚨🚔🚍🚘🚖🚡🚠🚟🚃🚋🚞🚝🚄🚅🚈🚂🚆🚇🚊✈️🛫🛬🛩💺🛰🚀🛸🚁🛶⛵️🚤🛳⛴🚢⚓️⛽️🚧🚦🚥🚏🗺🗿🗽🗼🏰🏯🏟🎡🎢🎠⛲️⛱🏖🏝🏜🌋⛰🏔🗻🏕🏠🏡🏘🏚🏗🏭🏢🏬🏣🏤🏥🏦🏨🏪🏫🏩💒🏛⛪️🕌🕍🕋⛩🛤🗾🎑🏞🌅🌄🌠🎇🎆🌇🌆🏙🌃🌌🌉🌁⌚️📱📲💻⌨️🖥🖨🖱🖲🕹🗜💽💾💿📀📼📷📸📹🎥📽🎞📞☎️📟📠📺📻🎙🎚🎛🧭⏱⏲⏰🕰⌛️⏳📡🔋🔌💡🔦🕯🧯🛢💸💵💴💰💳💎⚖️🧰🔧🔨⚒🛠⛏🔩🧱⛓🧲💣🧨🔪🗡⚔️🛡🚬⚰️⚱️🏺🔮📿🧿💈🔭🔬🕳💊💉🧬🦠🧫🧪🌡🧹🧺🧻🚽🚰🚿🛁🛀🧼🧽🧴🛎🔑🗝🚪🛋🛌🧸🖼🛒🎁🎈🎏🎀🎊🎉🎎🏮🎐✉️📩📨📧💌📥📤📦🏷📪📫📬📭📮📯📜📃📄📑🧾📊📈📉🗒🗓📆📅🗑📇🗳🗄📋📁📂🗂🗞📰📓📔📒📕📗📘📙📚📖🔖🧷🔗📎🖇📐📏🧮📌📍✂️🖊🖋✒️🖌🖍📝✏️🔍🔎🔏🔐🔒🔓🔓❤️🧡💛💚💙💜🖤💔❣️💕💞💗💖💘💝💟☮️✝️☪️🕉☸️✡️🔯🕎☯️☦️🛐⛎♈️♉️♊️♋️♌️♍️♎️♏️♐️♑️♒️♓️🆔⚛️🉑☣️📴📳🈶🈚️🈸🈺🈷️✴️🆚💮🉐㊙️㊗️🈴🈵🈲🅰️🅱️🆎🆑🅾️🆘❌⭕️🛑⛔️📛🚫💯💢♨️🚷🚯🚱🔞📵🚭❗️❕❓❓❔‼️⁉️🔅🔆〽️⚠️🚸🔱⚜️🔰✅🈯️💹❇️✳️❎🌐💠Ⓜ️🌀💤🏧♿️🅿️🈳🈂️🛂🛃🛄🛅🚹🚺🚼🚻🚮🎦📶🈁🔣ℹ️🔤🔡🔠🆖🆗🆙🆙🆒🆕🆓0️⃣1️⃣2️⃣3️⃣4️⃣5️⃣6️⃣7️⃣8️⃣9️⃣🔟🔢#️⃣*️⃣▶️⏸⏯⏹⏺⏭⏮⏩⏪⏫⏬🔼🔽⬅️⬇️↘️↖️↕️↙️↗️⬆️➡️◀️⏏️↪️↩️↔️⤵️🔀🔁🔄🔃⤵️⤴️🎵🎶➕➖➗♾💲💱©️👁‍🗨🔚🔙🔛🔝🔜➰➿➿☑️🔘🔴🔵🔺🔻🔸🔹🔶🔷🔳🔲▫️◽️◻️⬜️🔈🔇🔉🔊🔔🔔🔔🔕📣📢💬💭🗯♣️♦️🃏🎴🕐🕑🕒🕓🕔🕕🕖🕗🕘🕙🕚🕛🕜🕝🕞🕟🕠🕡🕢🕣🕤🕥🕥🕦🕧🀄️♥️♠️⬛️◼️◾️▪️⚪️✔️〰️®️™️✖️⭐️🏴🏁🏴‍☠️🏳️🚩🏳️‍🌈🇺🇳🇮🇸🇮🇪🇦🇿🇦🇫🇺🇸🇦🇪🇩🇿🇦🇷🇦🇼🇦🇱🇦🇲🇦🇮🇦🇴🇦🇬🇦🇩🇾🇪🇬🇧🏴󠁧󠁢󠁳󠁣󠁴󠁿🏴󠁧󠁢󠁷󠁬󠁳󠁿🇮🇱🇮🇹🇮🇶🇮🇷🇮🇳🇮🇩🇼🇫🇺🇬🇺🇦🇺🇿🇺🇾🇪🇨🇪🇬🇪🇪🇪🇹🇪🇷🇸🇻🇦🇺🇦🇹🇦🇽🇴🇲🇳🇱🇧🇶🇬🇭🇨🇻🇬🇬🇬🇾🇰🇿🇶🇦🇨🇦🇮🇨🇬🇦🇨🇲🇬🇲🇰🇭🇬🇳🇬🇼🇨🇾🇨🇺🇨🇺🇨🇼🇬🇷🇰🇮🇰🇬🇬🇹🇬🇵🇬🇺🇰🇼🇨🇰🇬🇱🇨🇽🇬🇩🇭🇷🇰🇾🇰🇪🇨🇮🇨🇨🇨🇨🇨🇷🇽🇰🇰🇲🇨🇴🇨🇬🇨🇩🇸🇦🇬🇸🇼🇸🇧🇱🇸🇹🇿🇲🇵🇲🇸🇲🇸🇱🇩🇯🇬🇮🇯🇪🇯🇲🇬🇪🇸🇾🇸🇬🇸🇽🇿🇼🇨🇭🇸🇪🇸🇩🇪🇸🇸🇷🇱🇰🇸🇰🇸🇮🇸🇿🇸🇨🇸🇳🇷🇸🇰🇳🇻🇨🇸🇭🇸🇴🇸🇧🇹🇨🇹🇭🇹🇯🇹🇿🇨🇿🇹🇩🇹🇳🇨🇱🇹🇻🇩🇰🇩🇪🇹🇬🇹🇰🇩🇴🇩🇲🇹🇹🇹🇲🇹🇷🇹🇴🇳🇬🇳🇷🇳🇦🇳🇺🇳🇮🇳🇮🇳🇪🇳🇨🇳🇿🇳🇵🇳🇫🇳🇫🇳🇴🇧🇭🇭🇹🇵🇰🇻🇦🇵🇦🇻🇺🇧🇸🇵🇬🇧🇲🇵🇼🇵🇾🇧🇧🇭🇺🇧🇩🇵🇳🇫🇯🇵🇭🇫🇮🇧🇹🇵🇷🇫🇴🇫🇰🇧🇷🇫🇷🇧🇬🇧🇫🇧🇳🇧🇮🇻🇳🇧🇯🇻🇪🇧🇾🇧🇿🇵🇪🇧🇪🇵🇱🇧🇦🇧🇼🇧🇴🇵🇹🇭🇳🇲🇭🇲🇴🇲🇰🇲🇬🇾🇹🇲🇼🇲🇱🇲🇹🇲🇶🇲🇾🇮🇲🇫🇲🇲🇲🇲🇽🇲🇺🇲🇷🇲🇿🇲🇨🇲🇻🇲🇩🇲🇦🇲🇳🇲🇪🇲🇸🇯🇴🇱🇦🇱🇻🇱🇹🇱🇾🇱🇮🇱🇷🇷🇴🇱🇺🇷🇼🇱🇸🇱🇧🇷🇪🇷🇺🇮🇴🇻🇬🇰🇷🇪🇺🇰🇷🇭🇰🇪🇭🇬🇶🇨🇫🇨🇳🇹🇱🇿🇦🇸🇸🇦🇶🇯🇵🎌🇬🇫🇵🇫🇹🇫🇻🇮🇦🇸🇲🇵🇰🇵"
removeEmoji(allEmoji) of me
–> "1⃣2⃣3⃣‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‼⁉〽0⃣1⃣2⃣3⃣4⃣5⃣6⃣7⃣8⃣9⃣#⃣*⃣⬅⬇↘↖↕↙↗⬆↪↩↔⤵⤵⤴©‍〰®™‍‍󠁧󠁢󠁳󠁣󠁴󠁿󠁧󠁢󠁷󠁬󠁳󠁿"

on removeEmoji(aStr)
  set aNSString to current application’s NSString’s stringWithString:aStr
  
  
— Emoticons, Misc Symbols and Pictographs, Transport and Map, Misc symbols, Dingbats, Variation Selectors, Supplemental Symbols and Pictographs, Flags
  
return (aNSString’s stringByReplacingOccurrencesOfString:"[\\U0001F600-\\U0001F64F\\U0001F300-\\U0001F5FF\\U0001F680-\\U0001F6FF\\U00002600-\\U000026FF\\U00002700-\\U000027BF\\U0000FE00-\\U0000fE0F\\U0001F900-\\U0001F9FF\\U0001F1E6-\\U0001F1FF\\U00002B50-\\U00002B50\\U0000231A-\\U0000231B\\U00002328-\\U000023FA\\U000024C2-\\U000024C2\\U0001F194-\\U0001F194\\U0001F170-\\U0001F251\\U000025AB-\\U000025FE\\U00003297-\\U00003299\\U00002B55-\\U00002B55\\U00002139-\\U00002139\\U00002B1B-\\U00002B1C\\U000025AA-\\U000025AA\\U0001F004-\\U0001F004\\U0001F0CF-\\U0001F0CF]" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, aNSString’s |length|()}) as text
end removeEmoji

★Click Here to Open This Script 

Posted in regexp Text | Tagged 10.14savvy 10.15savvy NSRegularExpressionSearch NSString | 2 Comments

Numbersで選択範囲のセルから数字以外の文字を除去する

Posted on 8月 29, 2019 by Takaaki Naganoya

Numbersで選択範囲のセルから数字以外の文字を除去するAppleScriptです。

よく、Webブラウザ上で表示中の表データからNumbersなどの表計算ソフトにデータをコピー&ペーストして再利用することがあります。この際に、Webブラウザ上で選択中のDOM構造などを取得できると便利なのですが、いろいろ調べてみてもなかなか方法が見つかりません(自分が設計していたら、絶対に実装してるんですけれども)。

そこで、表データをWebブラウザから表計算ソフト上にコピー後にデータ加工することを考えることになります。

ExcelやNumbers上に表データをペーストして、その後で加工することをよく行います。手動で行うとかったるいので、選択範囲のセルを順次加工するScriptを日常的に作ってはストックしてあります(セル内の改行文字を削除するとか、いろいろ)。

本ScriptはmacOS 10.14.6+Numbers v6.1で検証してあります。

OS標準装備のScript Menuに入れて呼び出して利用しています。

もともと、Numbersのセル書き換え速度はそれほど速くないので、数百セルとか数千セルを一気に書き換えるような用途は考慮していません。そういう用途には、書き換えたデータをCSV書き出しして、CSVのファイルをNumbersでオープンするといった処理になると思います。

AppleScript名:選択範囲のセルから数字以外の文字を除去する
— Created 2019-08-29 by Takaaki Naganoya
— 2019 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

tell application "Numbers"
  tell front document
    tell active sheet
      try
        set theTable to first table whose class of selection range is range
      on error
        return false
      end try
      
      
tell theTable
        set cellList to cell of selection range
        
set mySelectedRanges to value of cell of selection range
        
set res2 to returnNumbersCharOnlyList(mySelectedRanges) of me
        
        
repeat with i from 1 to (length of cellList)
          ignoring application responses –Async Mode
            tell item i of cellList
              set value to item i of res2
            end tell
          end ignoring
        end repeat
        
      end tell
      
    end tell
  end tell
end tell

on returnNumbersCharOnlyList(aList)
  set nList to {}
  
repeat with i in aList
    set the end of nList to returnNumberCharsOnly(i) of me
  end repeat
  
return nList
end returnNumbersCharOnlyList

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

★Click Here to Open This Script 

Posted in list regexp Text | Tagged 10.12savvy 10.13savvy 10.14savvy NSRegularExpressionSearch NSString | Leave a comment

NumbersのColumn Adr(26進数)と10進数との相互変換

Posted on 7月 22, 2019 by Takaaki Naganoya

Numbersの表のカラムを表現するアドレス文字列(26進数)と数値の間のエンコーダーおよびデコーダーのAppleScriptです。

もともとは、Excel 2004/2008で採用されたカラムアドレス形式に対処するためのScriptでした。

Excel上のセルのアドレス(場所)を指し示す方法は、「R1C1」(行とカラムを数値指定)形式、あるいはAppleScriptの行オブジェクトとセルオブジェクトで指定する形式でした。

そこへ新たに「A1」形式……画面上で表記されている行、カラムと親和性の高い形式が採用されることになりました。当初は相互変換のための関数なども用意されていなかったと記憶しています(間違っていたらご指摘ください)。そのため、Scripterが自力でこのA1形式に対応する必要が出てきました。

そんな中、Excel書類にAppleScriptを埋め込んで実行するAppleScriptを開発。本ルーチンはそのScript開発のために作成したものです。

Excel 2008でVBAの処理系が外されてMac上のVBA的なマクロ処理はAppleSctiptに一本化されるという話になっていたため(当時の話)、これを好機ととらえ、マイクロソフトのご担当にデモして、US本社で紹介していただくということになりました。

ただ、その会議上でVBAの復活プランが発表され、自分の提案したプランは廃案に(まさか当時のREALbasicのコンパイラの開発者を引き抜いてきてVBAの処理系をスクラッチで書かせるとは思いませんでしたわー)。

その後は、Excel 2011でVBAの処理系が復活。本ルーチンも割とHDDの肥やしとして絶賛在庫状態になっておりました。ごくたまーに、このExcel 2011でVBAの処理系が復活したことを知らない方がいて、「VBAで動いているマクロをAppleScriptに移植してほしい」という問い合わせがあるのですが、「Excelの最新版を購入してください。VBAがありますよ」とお返事しています。最新のExcelが動く環境を購入する費用よりも安く仕事としてお受けすることは困難なので。

そこから年月が流れ、AppleがNumbersをリリース。そのカラム表記がExcel 2004/2008と同じ形式になっているために、しまいこんでいたルーチンをふたたび引っ張り出してきた次第です。

一応、条件つきで使えるものの、作りが古い(やっつけ仕事な)点が気になります。きっと、誰かがもっといいルーチンを作って使っているに違いありません。一応、本ルーチンでは1〜1351の範囲での動作を確認しています。

もう少し改良したいところではあります。実用上は、Numbersでそこまで大きなデータは扱わない(はず)ので、問題はあまりないものと思われます。

AppleScript名:NumbersのColumn Adr(26進数)と10進数との相互変換
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/07/21
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

property NSString : a reference to current application’s NSString
property NSArray : a reference to current application’s NSArray
property NSRegularExpressionSearch : a reference to current application’s NSRegularExpressionSearch

repeat with i from 1 to 1351
  set a to numAdrToColumnEncode(i) of me
  
set b to colAddrToNumDecode(a) of me
  
set aRes to (i = b) as boolean
  
log {i, b, a, aRes}
  
if aRes = false then display dialog i as string
end repeat

–10進数数値をExcel 2004/2008的カラム表現にエンコードするサブルーチン(エンコード範囲:1〜1351)
on numAdrToColumnEncode(origNum)
  if origNum > 1351 then
    error "エラー:Numbersのカラム表現(A1形式)への変換ルーチンにおいて、想定範囲外(1351以上)のパラメータが指定されました"
  end if
  
  
set upperDigitEncTable to {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A"}
  
set lowerDigitEncTable to {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "A"}
  
  
set oNum to origNum
  
set nTh to 26
  
set stringLength to 4
  
  
–数字が1桁の場合の対応
  
if origNum < 27 then
    set aRes to (item origNum of upperDigitEncTable) as string
    
return aRes
  end if
  
  
  
if origNum > 702 then
    –3桁になる場合
    
set upupNum to oNum div 676 –整数除算–上の上の桁
    
set oNum to oNum – (upupNum * 676)
    
set upNum to oNum div 26 –整数除算–上の桁
    
set lowNum to oNum mod 26 – 1 –余剰計算–下の桁
    
    
–log {origNum, upupNum, upNum, lowNum}
    
    
–超つじつま合わせルーチン【強引】
    
if lowNum = -1 then
      set upNum to upNum – 1
      
set lowNum to 25
    end if
    
    
set upupChar to (item upupNum of upperDigitEncTable) as string
    
set upChar to (item upNum of upperDigitEncTable) as string
    
set lowChar to (item (lowNum + 1) of lowerDigitEncTable) as string
    
set resText to upupChar & upChar & lowChar
    
  else
    –2桁の場合
    
set upNum to oNum div 26 –整数除算–上の桁
    
set lowNum to oNum mod 26 – 1 –余剰計算–下の桁
    
    
    
–超つじつま合わせルーチン【強引】
    
if lowNum = -1 then
      set upNum to upNum – 1
      
set lowNum to 25
    end if
    
    
set upChar to (item upNum of upperDigitEncTable) as string
    
set lowChar to (item (lowNum + 1) of lowerDigitEncTable) as string
    
set resText to upChar & lowChar
    
  end if
  
  
return resText
  
end numAdrToColumnEncode

–Numbersの横方向アドレス(A〜Zの26進数)文字列を10進数に変換
on colAddrToNumDecode(origStr)
  return aNthToDecimal(origStr, {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}) of me
end colAddrToNumDecode

–n進数文字列を10進数に変換する
on aNthToDecimal(origStr, nTh)
  set resNumber to 0
  
  
set sList to reverse of (characters of origStr)
  
set aLen to length of nTh
  
set digitCount to 0
  
  
repeat with i in sList
    set j to contents of i
    
set aRes to offsetInList(j, nTh) of me
    
    
set resNumber to resNumber + (aLen ^ digitCount) * aRes
    
    
set digitCount to digitCount + 1
  end repeat
  
  
return resNumber as integer
end aNthToDecimal

on offsetInList(aChar, aList)
  set anArray to NSArray’s arrayWithArray:aList
  
set aInd to (anArray’s indexOfObject:aChar)
  
if aInd = current application’s NSNotFound or (aInd as number) > 9.99999999E+8 then
    error "Invalid Character Error"
  else
    return (aInd as integer) + 1 –0 to 1 based index conversion
  end if
end offsetInList

★Click Here to Open This Script 

Posted in list Number | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSArray NSRegularExpressionSearch NSString Numbers | Leave a comment

Google Sheets URLから正規表現でIDを抽出 v2

Posted on 4月 18, 2019 by Takaaki Naganoya

文字列で与えられたGoogle SpreadSheetsのURLから正規表現の機能を用いてSheets IDを抽出するAppleScriptです。

初回掲載時の内容にShane Stanleyから「長さが0の文字列」(zero length string)に対応できていないので、変更したほうがいいよ、という助言をもらったので書き換えました(Thanks Shane!)。

AppleScript名:Google Sheets URLから正規表現でIDを抽出 v2
— Created 2019-04-18 by Takaaki Naganoya
— Modified 2019-04-19 by Shane Stanley
use AppleScript version "2.5" –macOS 10.11 or later
use scripting additions
use framework "Foundation"

property NSString : a reference to current application’s NSString
property NSRegularExpressionSearch : a reference to current application’s NSRegularExpressionSearch

–https://developers.google.com/sheets/guides/concepts?hl=ja
set aURLText to "https://docs.google.com/spreadsheets/d/1qpyC0XzvTcKT6EISywvqESX3A0MwQoFDE8p-Bll4hps/edit#gid=0
"

set sheetsID to (stripGoogleSheetsIDFromURL(aURLText) of me) as string
–> "1qpyC0XzvTcKT6EISywvqESX3A0MwQoFDE8p-Bll4hps"

set aURLText to "" –Zero Length String
set sheetsID to (stripGoogleSheetsIDFromURL(aURLText) of me) as string
–> ""

on stripGoogleSheetsIDFromURL(aText as string)
  set sStrHead to "/spreadsheets/d/"
  
set regStr to sStrHead & "([a-zA-Z0-9-_]+)"
  
  
set anNSString to NSString’s stringWithString:aText
  
set aRange to anNSString’s rangeOfString:regStr options:(NSRegularExpressionSearch)
  
  
–if aRange = {location:0, length:0} then return ""–v1
  
if |length| of aRange = 0 then return "" –Prepare for zero length strings(Thanks Shane!)
  
  
set bStr to anNSString’s substringWithRange:aRange
  
set theString to bStr’s stringByReplacingOccurrencesOfString:sStrHead withString:"" options:(NSRegularExpressionSearch) range:{location:0, |length|:length of sStrHead}
  
  
return theString as string
end stripGoogleSheetsIDFromURL

★Click Here to Open This Script 

Posted in regexp Text URL | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSRegularExpressionSearch NSString | Leave a comment

青空文庫のテキストのルビタグを超高速削除

Posted on 3月 18, 2019 by Takaaki Naganoya

青空文庫のテキストのルビタグをすべて削除するAppleScriptです。

CotEditorでオープン中の青空文庫のテキストからルビタグを削除し、元のドキュメントに置換結果を反映させます。

テストに使用したのは、夏目漱石の「こころ」のテキストです。上記ページの「テキストファイル(ルビあり)」をダウンロードして、Zipアーカイブを展開して使用しました。

ファイルサイズ373KB、当該部分4,570箇所。開始文字「《」、終了文字「》」で囲われたエリアをすべて削除するという、AppleScriptにはあからさまに不得意そうな処理で、最初に書いたAppleScriptでは1分半以上かかっていました。内容は、おおよそ常識的なサブルーチンを組み合わせてループで回しただけです。わざと遅くなるように組んだりはしていません。

これを、

 (1)CotEditorからの文章テキストの取得
 (2)置換当該箇所のリストアップ
 (3)文字置換
 (4)CotEditorへの文章テキストの転送

の4つのステージに分け、それぞれ処理時間を計測。すると、(1)、(2)、(4)については1秒かかるかかからないかぐらいの速度で実行していることが判明。圧倒的に(3)文字置換の処理に時間がかかっていました。

もともと文字置換には、AppleScript処理系最速のtext item delimitersを用いるサブルーチンを使用していました。これ以上、この方向に頑張っても速く処理することはできません。一応、ダメ元で4,570個の要素を持つ巨大なtext item delimitersを作成し一括処理できないか試してみたものの、さすがに処理系のキャパシティを超過しているようで処理が戻ってきません(迷走状態)。完全にお手上げです。

そこで、AppleScriptの処理系に依存したtext item delimitersによる処理をやめ、メモリ管理効率がよくないAppleScriptのstring型のデータで保持することをやめ、置換のたびにAppleScriptのstring型に変換(cast)することをやめ、置換中は最初から最後までNSMutableStringで管理するようにしました。

このように大幅に書き換えたところ、トータルで3.58秒で処理終了するようになりました。

すべての置換が終了したあとにNSMutableStringをAppleScriptのstringに変換し、CotEditorの最前面のドキュメントに結果を転送しています。

AppleScript名:青空文庫のテキストのルビタグを削除
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/03/18
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

property NSScanner : a reference to current application’s NSScanner
property NSOrderedSet : a reference to current application’s NSOrderedSet
property NSMutableString : a reference to current application’s NSMutableString
property NSRegularExpressionSearch : a reference to current application’s NSRegularExpressionSearch

tell application "CotEditor"
  tell front document
    set aCon to contents
  end tell
end tell

set bCon to trimStrFromTo(aCon, "《", "》") of me

tell application "CotEditor"
  tell front document
    set contents to bCon
  end tell
end tell

–開始文字と終了文字に囲われた文字列をすべて削除する
on trimStrFromTo(aParamStr, fromStr, toStr)
  script hsAry
    property anArray : {}
    
property curStr : ""
  end script
  
  
set theScanner to NSScanner’s scannerWithString:aParamStr
  
set (anArray of hsAry) to {}
  
  
repeat until (theScanner’s isAtEnd as boolean)
    set {aResult, theKey} to theScanner’s scanUpToString:fromStr intoString:(reference)
    
theScanner’s scanString:fromStr intoString:(missing value)
    
    
set {bResult, theValue} to theScanner’s scanUpToString:toStr intoString:(reference)
    
if theValue is missing value then set theValue to ""
    
    
theScanner’s scanString:toStr intoString:(missing value)
    
set the end of (anArray of hsAry) to (fromStr & theValue & toStr)
  end repeat
  
  
–Case: Not found
  
if length of (anArray of hsAry) = 0 then return aParamStr
  
  
–Uniquefy
  
set (anArray of hsAry) to makeUniqueListFrom((anArray of hsAry)) of me
  
  
–Replace strings as NSMutableString
  
set (curStr of hsAry) to NSMutableString’s stringWithString:aParamStr
  
repeat with i in (anArray of hsAry)
    set j to contents of i
    
set (curStr of hsAry) to ((curStr of hsAry)’s stringByReplacingOccurrencesOfString:(j) withString:"" options:(NSRegularExpressionSearch) range:{location:0, |length|:((curStr of hsAry)’s |length|())})
  end repeat
  
  
return (curStr of hsAry) as string
end trimStrFromTo

–1D Listをユニーク化(重複削除)
on makeUniqueListFrom(theList)
  set theSet to NSOrderedSet’s orderedSetWithArray:theList
  
return (theSet’s array()) as list
end makeUniqueListFrom

★Click Here to Open This Script 

Posted in list Text | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy CotEditor NSMutableString NSOrderedSet NSRegularExpressionSearch NSScanner | 2 Comments

1D Listのうち指定文字種で構成される要素のみ抽出

Posted on 12月 20, 2018 by Takaaki Naganoya

1D List(配列)に入れた文字要素を文字種類で該当するものだけ抽出するAppleScriptです。

文字種類でデータ抽出する、という用途はけっこう多いので、単体で使えるようにしておきました。プログラムを見ていただくとわかるとおり、

 数字:”9″
 英字:”A”
 半角記号:”$”
 ひらがな:”ひ”
 カタカナ:”カ”
 漢字:”漢”

で文字種類を指定します。

以前のバージョンではありもののルーチンを組み合わせただけなので、全体的に無駄があって処理速度についてはあまり感心できないレベルだったので、若干の高速化を図りました(繰り返し処理部分で無駄な演算を省略)。

ただし、「ひらがな+カタカナは許容する」というふうに、複数の文字種を許可する例が多いので、これではまだ実用レベルには達していないと思います。

AppleScript名:1D Listのうち指定文字種で構成される要素のみ抽出
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/12/20
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property NSString : a reference to current application’s NSString
property NSScanner : a reference to current application’s NSScanner
property NSNumber : a reference to current application’s NSNumber
property NSDictionary : a reference to current application’s NSDictionary
property NSCountedSet : a reference to current application’s NSCountedSet
property NSCharacterSet : a reference to current application’s NSCharacterSet
property NSMutableArray : a reference to current application’s NSMutableArray
property NSNumberFormatter : a reference to current application’s NSNumberFormatter
property NSMutableCharacterSet : a reference to current application’s NSMutableCharacterSet
property NSRegularExpressionSearch : a reference to current application’s NSRegularExpressionSearch
property NSNumberFormatterRoundUp : a reference to current application’s NSNumberFormatterRoundUp
property NSStringTransformFullwidthToHalfwidth : a reference to current application’s NSStringTransformFullwidthToHalfwidth

set aList to {"Naganoya", "ながのや", "ナガノヤ", "長野谷"} –Alphabet, Hiragana, Katakana, Kanji

set aRes to filterByCharKind(aList, "A") of me –アルファベットで構成される要素のみ抽出
–> {"Naganoya"}

set bRes to filterByCharKind(aList, "ひ") of me –ひらがなだけで構成される要素のみ抽出
–> {"ながのや"}

set cRes to filterByCharKind(aList, "カ") of me –カタカナだけで構成される要素のみ抽出
–> {"ナガノヤ"}

set dRes to filterByCharKind(aList, "漢") of me –漢字だけで構成される要素のみ抽出
–> {"長野谷"}

–文字種別を判定して指定文字種のみから構成されるものを抽出
on filterByCharKind(aList as list, targCharKind as string)
  set dList to {}
  
repeat with i in aList
    set j to contents of i
    
set tmpPat to retAtrPatternFromStr(j) of me
    
if tmpPat is equal to {targCharKind} then
      set the end of dList to j
    end if
  end repeat
  
  
return dList
end filterByCharKind

–Objective-Cライクなパラメータ記述
on makeUniqueListOf:theList
  set theSet to current application’s NSOrderedSet’s orderedSetWithArray:theList
  
return (theSet’s array()) as list
end makeUniqueListOf:

–Pure AS風のパラメータ記述
on makeUniqueListFrom(theList)
  set aList to my makeUniqueListOf:theList
  
return aList
end makeUniqueListFrom

–1D Listを文字列長でソート v2
on sort1DListByStringLength(aList as list, sortOrder as boolean)
  set aArray to current application’s NSArray’s arrayWithArray:aList
  
set desc1 to current application’s NSSortDescriptor’s sortDescriptorWithKey:"length" ascending:sortOrder
  
set desc2 to current application’s NSSortDescriptor’s sortDescriptorWithKey:"self" ascending:true selector:"localizedCaseInsensitiveCompare:"
  
set bArray to aArray’s sortedArrayUsingDescriptors:{desc1, desc2}
  
return bArray as list of string or string
end sort1DListByStringLength

–文字種別の判定
on retAtrPatternFromStr(aText as string)
  set b1List to {"9", "A", "$", "漢", "ひ", "カ"} –数字、アルファベット、記号、全角漢字、全角ひらがな、全角カタカナ
  
  
–set cStr to zenToHan(aText) of me
  
  
set outList to {}
  
set cList to characters of (aText)
  
  
repeat with i in cList
    set j to contents of i
    
    
set chk1 to ((my chkNumeric:j) as integer) * 1
    
set chk2 to ((my chkAlphabet:j) as integer) * 2
    
set chk3 to ((my chkSymbol:j) as integer) * 3
    
set chk4 to ((my chkKanji:j) as integer) * 4
    
set chk5 to ((my chkHiragana:j) as integer) * 5
    
set chk6 to ((my chkKatakana:j) as integer) * 6
    
    
set itemVal to (chk1 + chk2 + chk3 + chk4 + chk5 + chk6)
    
    
–if itemVal > 0 then
    
set aVal to (contents of item itemVal of b1List)
    
    
if aVal is not in outList then
      set the end of outList to aVal
    end if
    
–end if
  end repeat
  
  
return outList
end retAtrPatternFromStr

–全角→半角変換
on zenToHan(aStr)
  set aString to NSString’s stringWithString:aStr
  
return (aString’s stringByApplyingTransform:(NSStringTransformFullwidthToHalfwidth) |reverse|:false) as string
end zenToHan

–数字か
on chkNumeric:checkString
  set digitCharSet to NSCharacterSet’s characterSetWithCharactersInString:"0123456789"
  
set ret to my chkCompareString:checkString baseString:digitCharSet
  
return ret as boolean
end chkNumeric:

–記号か
on chkSymbol:checkString
  set muCharSet to NSCharacterSet’s alloc()’s init()
  
muCharSet’s addCharactersInString:"$\"!~&=#[]._-+`|{}?%^*/’@-/:;(),"
  
set ret to my chkCompareString:checkString baseString:muCharSet
  
return ret as boolean
end chkSymbol:

–漢字か
on chkKanji:aChar
  return detectCharKind(aChar, "[一-龠]") of me
end chkKanji:

–ひらがなか
on chkHiragana:aChar
  return detectCharKind(aChar, "[ぁ-ん]") of me
end chkHiragana:

–カタカナか
on chkKatakana:aChar
  return detectCharKind(aChar, "[ァ-ヶ]") of me
end chkKatakana:

–半角スペースか
on chkSpace:checkString
  set muCharSet to NSCharacterSet’s alloc()’s init()
  
muCharSet’s addCharactersInString:" " –半角スペース(20h)
  
set ret to my chkCompareString:checkString baseString:muCharSet
  
return ret as boolean
end chkSpace:

— アルファベットか
on chkAlphabet:checkString
  set aStr to NSString’s stringWithString:checkString
  
set allCharSet to NSMutableCharacterSet’s alloc()’s init()
  
allCharSet’s addCharactersInRange:({location:97, |length|:26}) –97 = id of "a"
  
allCharSet’s addCharactersInRange:({location:65, |length|:26}) –65 = id of "A"
  
set aBool to my chkCompareString:aStr baseString:allCharSet
  
return aBool as boolean
end chkAlphabet:

on chkCompareString:checkString baseString:baseString
  set aScanner to NSScanner’s localizedScannerWithString:checkString
  
aScanner’s setCharactersToBeSkipped:(missing value)
  
aScanner’s scanCharactersFromSet:baseString intoString:(missing value)
  
return (aScanner’s isAtEnd()) as boolean
end chkCompareString:baseString:

on detectCharKind(aChar, aPattern)
  set aChar to NSString’s stringWithString:aChar
  
set searchStr to NSString’s stringWithString:aPattern
  
set matchRes to aChar’s rangeOfString:searchStr options:(NSRegularExpressionSearch)
  
if matchRes’s location() = (current application’s NSNotFound) or (matchRes’s location() as number) > 9.99999999E+8 then
    return false
  else
    return true
  end if
end detectCharKind

★Click Here to Open This Script 

Posted in list regexp Text | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSCharacterSet NSCountedSet NSDictionary NSMutableArray NSMutableCharacterSet NSNumber NSNumberFormatter NSNumberFormatterRoundUp NSRegularExpressionSearch NSScanner NSString NSStringTransformFullwidthToHalfwidth | Leave a comment

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

Google Search

Popular posts

  • macOS 13, Ventura(継続更新)
  • アラートダイアログ上にWebViewで3Dコンテンツを表示(WebGL+three.js)v3
  • UI Browserがgithub上でソース公開され、オープンソースに
  • Xcode 14.2でAppleScript App Templateを復活させる
  • macOS 13 TTS Voice環境に変更
  • 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