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

system_profilerの結果のstringのplistをdictionaryにのコピー2

Posted on 2月 7, 2018 by Takaaki Naganoya
AppleScript名:system_profilerの結果のstringのplistをdictionaryにのコピー2
— Created 2015-11-01 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aTargKey to "machine_name"
set aTargGenre to "SPHardwareDataType"

set macRes to getSystemProfileInAGenre(aTargGenre, aTargKey) of me
–>  "MacBook Pro"

on getSystemProfileInAGenre(aTargGenre, aTargKey)
  set sRes to do shell script ("/usr/sbin/system_profiler -xml " & aTargGenre)
  
set aSource to (my readPlistFromStr:sRes) as list
  
set aaList to contents of first item of aSource
  
  
set aList to _items of aaList
  
repeat with i in aList
    set aDict to (current application’s NSMutableDictionary’s dictionaryWithDictionary:(contents of i))
    
set aKeyList to (aDict’s allKeys()) as list
    
if aTargKey is in aKeyList then
      set aRes to (aDict’s valueForKeyPath:aTargKey)
      
if aRes is not equal to missing value then
        return aRes as string
      end if
    end if
  end repeat
  
  
return false
end getSystemProfileInAGenre

–stringのplistを読み込んでRecordに
on readPlistFromStr:theString
  set aSource to current application’s NSString’s stringWithString:theString
  
set pListData to aSource’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set aPlist to current application’s NSPropertyListSerialization’s propertyListFromData:pListData mutabilityOption:(current application’s NSPropertyListImmutable) |format|:(current application’s NSPropertyListFormat) errorDescription:(missing value)
  
return aPlist
end readPlistFromStr:

★Click Here to Open This Script 

Posted in Record | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

XPathQuery4ObjCのじっけん2

Posted on 2月 7, 2018 by Takaaki Naganoya

XMLに対して、オープンソースの「XPathQuery4ObjC」を用いてXPathを指定してXML内の要素にアクセスするAppleScriptです。

XMLに対してXpathを指定してアクセスする道具はいろいろあります。

Syetem Eventsを使ってXMLにアクセスする方法、XMLLib OSAX、オープンソースのObjective-CのプログラムをCocoa Framework化したもの、etc。

ただ、macOS 10.14でOSAXが事実上使えなくなったことを考えると、OSAXによるAppleScriptの予約語拡張は得策ではありません。System Eventsも1つの解決策ではありますが、XPathが使えないのでほとんど使いません。

こうしたObjective-Cで記述されたプログラムをAppleScriptから呼び出すのが、現状でもっとも効率のよい解決策です。各プログラムはだいたいにおいて挙動が異なり、XMLの構造も一様ではありません。複数のプログラムをためして、対象のXMLを思い通りに処理できるか、総当たりで確認しています。

–> XPathQueryKit.framework

AppleScript名:XPathQuery4ObjCのじっけん2
— Created 2017-01-05 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "XPathQueryKit"
–https://github.com/cybergarage/XPathQuery4ObjC
–http://piyocast.com/as/archives/4376

set rssURL to current application’s |NSURL|’s URLWithString:"http://piyocast.com/as/feed"
set xpathQuery to current application’s CGXPathQuery’s alloc()’s initWithContentsOfURL:rssURL

if ((xpathQuery’s parse()) as boolean) = true then
  set entriesList to xpathQuery’s objectsForXPath:"/rss/channel/item"
  
  
repeat with itemObject in entriesList
    set aChild to itemObject’s children()
    
log aChild
    
    
set aTitle to (itemObject’s valueForXPath:"title")
    
log aTitle as string
    
    
set aLink to (itemObject’s valueForXPath:"link")
    
log aLink as string
    
    
set aComments to (itemObject’s valueForXPath:"comments")
    
log aComments as string
    
    
set aPubdate to (itemObject’s valueForXPath:"pubDate")
    
log aPubdate as string
    
    
set aCreator to (itemObject’s valueForXPath:"dc:creator")
    
log aCreator as string
    
    
set aCategory to (itemObject’s valuesForXPath:"category")
    
log aCategory as list
    
    
set aGUID to (itemObject’s valuesForXPath:"guid")
    
log aGUID as string
    
    
set aDesc to (itemObject’s valueForXPath:"description")
    
log aDesc as string
    
    
set aCommentURL to (itemObject’s valueForXPath:"wfw:commentRss")
    
log aCommentURL as string
  end repeat
  
end if

★Click Here to Open This Script 

Posted in Record | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

recordをXMLに v2

Posted on 2月 7, 2018 by Takaaki Naganoya
AppleScript名:recordをXMLに v2
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set theRecord to {firstName:"Saga", lastName:"Norén", city:"Malmö"}
makeXMLDocWithRecord(theRecord)
–>
(*
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<character>\n <firstName>Saga</firstName>\n <city>Malm
ö</city>\n <lastName>Norén</lastName>\n</character>"
*)

set theRecord to {firstName:"Saga", lastName:"Norén", city:"Malmö", partner:{firstName:"Martin", lastName:"Rohde", city:"København"}}
makeXMLDocWithRecord(theRecord)
–>
(*
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<character>\n <firstName>Saga</firstName>\n <lastName>Nor
én</lastName>\n <city>Malmö</city>\n <partner>\n <firstName>Martin</firstName>\n <city>København</city>\n <lastName>Rohde</lastName>\n </partner>\n</character>"
*)

–Record –> XML (text)
on makeXMLDocWithRecord(theRecord)
  — make root element
  
set rootElement to current application’s NSXMLNode’s elementWithName:"character"
  
  
— make XML document
  
set theXMLDocument to current application’s NSXMLDocument’s alloc()’s initWithRootElement:rootElement
  
theXMLDocument’s setDocumentContentKind:(current application’s NSXMLDocumentXMLKind)
  
theXMLDocument’s setStandalone:true
  
theXMLDocument’s setCharacterEncoding:"UTF-8"
  
  
— make dictionary from record
  
set anNSDictionary to current application’s NSDictionary’s dictionaryWithDictionary:theRecord
  
  
— add children to root element
  
its addChildTo:rootElement withDictionary:anNSDictionary
  
  
— return as string with whatever formatting options you want
  
return (theXMLDocument’s XMLStringWithOptions:(current application’s NSXMLNodePrettyPrint)) as text
end makeXMLDocWithRecord

on addChildTo:parentElement withDictionary:theDict
  set theKeys to theDict’s allKeys() as list
  
repeat with i from 1 to count of theKeys
    set theKey to item i of theKeys
    
set theValue to (theDict’s objectForKey:theKey)
    
set newElement to (current application’s NSXMLNode’s elementWithName:theKey)
    (
parentElement’s addChild:newElement)
    
if (theValue’s isKindOfClass:(current application’s NSDictionary)) as boolean then
      (its addChildTo:newElement withDictionary:theValue)
    else
      (newElement’s setObjectValue:theValue)
    end if
  end repeat
end addChildTo:withDictionary:

★Click Here to Open This Script 

Posted in Record | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

XmlToDictKitでXMLをDictionaryに(remote file)

Posted on 2月 7, 2018 by Takaaki Naganoya

–> XmlToDictKit.framework

AppleScript名:XmlToDictKitでXMLをDictionaryに(remote file)
— Created 2016-11-05 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "XmlToDictKit" –https://github.com/nicklockwood/XMLDictionary

set aURL to current application’s |NSURL|’s alloc()’s initWithString:"http://www.ibiblio.org/xml/examples/shakespeare/all_well.xml"
set xmlString to current application’s NSString’s alloc()’s initWithContentsOfURL:aURL encoding:(current application’s NSUTF8StringEncoding) |error|:(missing value)
if xmlString = missing value then return false
set xmlDoc to (current application’s NSDictionary’s dictionaryWithXMLString:xmlString) as record

★Click Here to Open This Script 

Posted in Record | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

XmlToDictKitでXMLをDictionaryに(local file)

Posted on 2月 7, 2018 by Takaaki Naganoya

–> XmlToDictKit.framework

AppleScript名:XmlToDictKitでXMLをDictionaryに(local file)
— Created 2016-11-05 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "XmlToDictKit" –https://github.com/nicklockwood/XMLDictionary

set aFile to POSIX path of (choose file)
set aURL to current application’s |NSURL|’s fileURLWithPath:aFile
set xmlString to current application’s NSString’s alloc()’s initWithContentsOfURL:aURL encoding:(current application’s NSUTF8StringEncoding) |error|:(missing value)
if xmlString = missing value then return false
set xmlDoc to (current application’s NSDictionary’s dictionaryWithXMLString:xmlString) as record

★Click Here to Open This Script 

Posted in Record | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

XMLをrecordにv2

Posted on 2月 7, 2018 by Takaaki Naganoya

XMLを解釈してAppleScriptのレコード型のデータに変換するAppleScriptです。

ひとことにXMLといっても、割と書き方にばらつきがあり、1つのルーチンやライブラリで解決できるというものでもない、ということを日々痛感しています。

さまざまな処理方法をおこなうXML解釈プログラムを用意しておいて、かたっぱしから試して適合するものを使っているというところです。本ルーチンで処理できる(解釈しやすい結果を出せる)XMLもあれば、そうでないものもあることでしょう。

また、解釈したXMLのタグについてもそのままではAppleScriptで取り扱えない(スペースを含むとか、特殊文字を含むとか)ものもあり、

  XML → NSDictionary → Record

と、AppleScriptのRecordまで変換してしまうと逆に取り扱いにくい場合もあるため、

  XML → NSDictionary

と、とどめておいて適宜NSDictionaryからデータを取り出すような処理を行うこともあります。

AppleScript名:XMLをrecordにv2
–2015 Shane Stanley & Alex Zavatone
— Modified 2016-11-06 by Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property dictStack : missing value — stack to hold array of dictionaries
property textInProgress : "" — string to collect text as it is found
property anError : missing value — if we get an error, store it here

set xmlRes to my makeRecordWithXML:(returnData() of me)
–> {|character|:{firstName:{|contents|:"Saga"}, lastName:{|contents|:"Norén"}, city:{|contents|:"Malmö"}, partner:{firstName:{|contents|:"Martin"}, lastName:{|contents|:"Rohde"}, city:{|contents|:"København"}, attributes:{approach:"dogged"}}}}

on makeRecordWithXML:xmlString
  — set up properties
  
set my dictStack to current application’s NSMutableArray’s array() — empty mutable array
  
set anEmpty to current application’s NSMutableDictionary’s |dictionary|()
  (
my dictStack)’s addObject:anEmpty — add empty mutable dictionary
  
set my textInProgress to current application’s NSMutableString’s |string|() — empty mutable string
  
  
— convert XML from string to data
  
set anNSString to current application’s NSString’s stringWithString:xmlString
  
set theData to anNSString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
  
— initialize an XML parser with the data
  
set theNSXMLParser to current application’s NSXMLParser’s alloc()’s initWithData:theData
  
  
— set this script to be the parser’s delegate
  
theNSXMLParser’s setDelegate:me
  
  
— tell it to parse the XML
  
set theResult to theNSXMLParser’s parse()
  
if theResult then — went OK, get first item on stack
    return ((my dictStack)’s firstObject()) –as record
  else — error, so return error
    error (my anError’s localizedDescription() as text)
  end if
end makeRecordWithXML:

— this is an XML parser delegate method. Called when new element found
on parser:anNSXMLParser didStartElement:elementName namespaceURI:aString qualifiedName:qName attributes:aRecord
  — store reference to last item on the stack
  
set parentDict to my dictStack’s lastObject()
  
  
— make new child
  
set childDict to current application’s NSMutableDictionary’s |dictionary|()
  
  
— if there are attributes, add them as a record with key "attributes"
  
if aRecord’s |count|() > 0 then
    childDict’s setValue:aRecord forKey:"attributes"
  end if
  
  
— see if there’s already an item for this key
  
set existingValue to parentDict’s objectForKey:elementName
  
  
if existingValue is not missing value then
    — there is, so if it’s an array, store it…
    
if (existingValue’s isKindOfClass:(current application’s NSMutableArray)) as boolean then
      set theArray to existingValue
    else
      — otherwise create an array and add it
      
set theArray to current application’s NSMutableArray’s arrayWithObject:existingValue
      
parentDict’s setObject:theArray forKey:elementName
    end if
    
    
— then add the new dictionary to the array
    
theArray’s addObject:childDict
  else
    — add new dictionary directly to the parent
    
parentDict’s setObject:childDict forKey:elementName
  end if
  
  
— also add the new dictionary to the end of the stack
  (
my dictStack)’s addObject:childDict
end parser:didStartElement:namespaceURI:qualifiedName:attributes:

— this is an XML parser delegate method. Called at the end of an element
on parser:anNSXMLParser didEndElement:elementName namespaceURI:aString qualifiedName:qName
  — if any text has been stored, add it as a record with key "contents"
  
if my textInProgress’s |length|() > 0 then
    set dictInProgress to my dictStack’s lastObject()
    
dictInProgress’s setObject:textInProgress forKey:"contents"
    
    
— reset textInProgress property for next element
    
set my textInProgress to current application’s NSMutableString’s |string|()
  end if
  
  
— remove last item from the stack
  
my dictStack’s removeLastObject()
end parser:didEndElement:namespaceURI:qualifiedName:

— this is an XML parser delegate method. Called when string is found. May be called repeatedly
on parser:anNSXMLParser foundCharacters:aString
  — only append string if it’s not solely made of space characters (which should be, but aren’t, caught by another delegate method)
  
if (aString’s stringByTrimmingCharactersInSet:(current application’s NSCharacterSet’s whitespaceAndNewlineCharacterSet()))’s |length|() > 0 then
    (my textInProgress)’s appendString:aString
  end if
end parser:foundCharacters:

— this is an XML parser delegate method. Called when there’s an error
on parser:anNSXMLParser parseErrorOccurred:anNSError
  set my anError to anNSError
end parser:parseErrorOccurred:

on returnData()
  return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<rss version=\"2.0\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:dcndl=\"http://ndl.go.jp/dcndl/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcmitype=\"http://purl.org/dc/dcmitype/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:openSearch=\"http://a9.com/-/spec/opensearchrss/1.0/\" xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">
<channel>
<title>Mac使いへの道 – 国立国会図書館サーチ OpenSearch</title>
<link>http://iss.ndl.go.jp/api/opensearch?title=Mac%E4%BD%BF%E3%81%84%E3%81%B8%E3%81%AE%E9%81%93</link>
<description>Search results for title=Mac使いへの道 </description>
<language>ja</language>
<openSearch:totalResults>1</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage></openSearch:itemsPerPage>
<item>
<title>Mac使いへの道</title>
<link>http://iss.ndl.go.jp/books/R100000002-I000003026578-00</link>
<description>
<![CDATA[<p>ソフトバンクパブリッシング,4797316489</p>
<ul><li>タイトル: Mac使いへの道</li>
<li>タイトル(読み): Macツカイ エノ ミチ</li>
<li>責任表示: 長野谷隆昌 著,</li>
<li>NDC(9): 548.29</li>
</ul>]]>
</description>
<author>長野谷隆昌 著,</author>
<category>本</category>
<guid isPermaLink=\"true\">http://iss.ndl.go.jp/books/R100000002-I000003026578-00</guid>
<pubDate>Thu, 08 May 2003 09:00:00 +0900</pubDate>
<dc:title>Mac使いへの道</dc:title>
<dcndl:titleTranscription>Macツカイ エノ ミチ</dcndl:titleTranscription>
<dc:creator>長野谷隆昌 著</dc:creator>
<dc:publisher>ソフトバンクパブリッシング</dc:publisher>
<dcterms:issued xsi:type=\"dcterms:W3CDTF\">2001</dcterms:issued>
<dc:identifier xsi:type=\"dcndl:ISBN\">4797316489</dc:identifier>
<dc:identifier xsi:type=\"dcndl:JPNO\">20206272</dc:identifier>
<dc:subject>コンピュータ</dc:subject>
<dc:subject xsi:type=\"dcndl:NDLC\">M154</dc:subject>
<dc:subject xsi:type=\"dcndl:NDC9\">548.29</dc:subject>
<dcterms:description>文献あり</dcterms:description>
<rdfs:seeAlso rdf:resource=\"http://id.ndl.go.jp/bib/000003026578\"/>
</item>
</channel>
</rss>"
end returnData

★Click Here to Open This Script 

Posted in Record | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

PKXMLKitでRSSをrecordに

Posted on 2月 7, 2018 by Takaaki Naganoya

–> PKXMLKit.framework

AppleScript名:PKXMLKitでRSSをrecordに
— Created 2017-12-18 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "PKXMLKit" –https://github.com/pawankv89/PKXMLParser

set aURL to "http://piyocast.com/as/feed/"
set aXMLURL to current application’s |NSURL|’s URLWithString:aURL
set xmlString to current application’s NSString’s alloc()’s initWithContentsOfURL:aXMLURL encoding:(current application’s NSUTF8StringEncoding) |error|:(missing value)
set xmlDoc to current application’s NSDictionary’s dictionaryWithXMLString:xmlString
set titleList to (xmlDoc’s valueForKeyPath:"channel.item.title") as list
–>  {​​​​​"アドウェア「OSX.Pirrit」のAppleScriptコードを読んでみた", ​​​​​"表示中のCotEditor書類の「次」のファイルを縦書きでオープン", ​​​​​"ハンドラ間接呼び出し", ​​​​​…}

★Click Here to Open This Script 

Posted in Record | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

recordをJSON文字列に

Posted on 2月 7, 2018 by Takaaki Naganoya

recordをJSON文字列に変換するAppleScriptです。

AppleScript名:recordをJSON文字列に.scpt
— Created 2015-07-20 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aRec to {abc:"test", bcd:"test2", cde:"test3"}
set aJson to convRecToJson(aRec) of me as string
–>   "{"abc":"test","bcd":"test2","cde":"test3"}"

on convRecToJson(aRec)
  set aDict to current application’s NSDictionary’s dictionaryWithDictionary:aRec
  
set jsonData to current application’s NSJSONSerialization’s dataWithJSONObject:aDict options:(0 as integer) |error|:(missing value) –0 is NSJSONWritingPrettyPrinted
  
set resString to current application’s NSString’s alloc()’s initWithData:jsonData encoding:(current application’s NSUTF8StringEncoding)
  
return resString
end convRecToJson

★Click Here to Open This Script 

Posted in Record | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ASOCでjson文字列をrecordに

Posted on 2月 7, 2018 by Takaaki Naganoya
AppleScript名:ASOCでjson文字列をrecordに
— Created 2015-07-20 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set jsonText to "{\"abc\":\"test\",\"bcd\":\"test2\",\"cde\":\"test3\"}"

set jsonString to current application’s NSString’s stringWithString:jsonText
–>  (NSString) "{"abc":"test","bcd":"test2","cde":"test3"}"

set jsonData to jsonString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
–>  (NSData) <7b226162 63223a22 74657374 222c2262 6364223a 22746573 7432222c 22636465 223a2274 65737433 227d>

set aJsonDict to current application’s NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
–>  (NSDictionary) {​​​​​abc:"test", ​​​​​bcd:"test2", ​​​​​cde:"test3"​​​}

set aRec to aJsonDict as record
–>  {​​​​​abc:"test", ​​​​​bcd:"test2", ​​​​​cde:"test3"​​​}

★Click Here to Open This Script 

Posted in JSON Record | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

NSDictionaryを値とキーの列挙で作成する 2

Posted on 2月 7, 2018 by Takaaki Naganoya
AppleScript名:NSDictionaryを値とキーの列挙で作成する 2
— Created 2017-03-03 01:16:41 +0900 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set bundleList to {"com.apple.filemerge", "com.barebones.bbedit", "com.barebones.textwrangler"}
set dummyList to {"fdummy", "bbedummy", "twdummy"}

set aDict to current application’s NSMutableDictionary’s dictionaryWithObjects:dummyList forKeys:bundleList
–>  (NSDictionary) {​​​​​com.apple.filemerge:"fdummy", ​​​​​com.barebones.textwrangler:"twdummy", ​​​​​com.barebones.bbedit:"bbedummy"​​​}

set aRes to aDict’s valueForKey:"com.barebones.bbedit"
–>  (NSString) "bbedummy"

★Click Here to Open This Script 

Posted in Record | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

NSDictionaryを値とキーの列挙で作成する

Posted on 2月 7, 2018 by Takaaki Naganoya
AppleScript名:NSDictionaryを値とキーの列挙で作成する
— Created 2016-03-02 23:34:42 +0900 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set eDic1 to current application’s NSDictionary’s dictionaryWithObjectsAndKeys_(42, "number", "Hello World", "string", missing value)
–>  (NSDictionary) {​​​​​number:42, ​​​​​string:"Hello World"​​​}

★Click Here to Open This Script 

Posted in Record | Tagged 10.11savvy 10.12savvy | Leave a comment

asoc_レコードをリストから生成

Posted on 2月 7, 2018 by Takaaki Naganoya
AppleScript名:asoc_レコードをリストから生成
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set labelList to {"Address", "Names"}
set valueList to {"ここらへん", "ぴよまるさん"}

set theResult to current application’s NSDictionary’s dictionaryWithObjects:(valueList) forKeys:(labelList)
set aRec to theResult as record

–> {Address:"ここらへん", Names:"ぴよまるさん"}

★Click Here to Open This Script 

Posted in Record | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ASOCでNSPredicateによる正規表現を併用した抽出

Posted on 2月 7, 2018 by Takaaki Naganoya
AppleScript名:ASOCでNSPredicateによる正規表現を併用した抽出
— Created 2015-09-28 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use BridgePlus : script "BridgePlus" —https://www.macosxautomation.com/applescript/apps/BridgePlus.html

set sampleList to {{textData:"Piyomaru", uID:1}, {textData:"Xx Piyomaru x", uID:2}, {textData:"xxxxx 11111111 98 x xxxxxxxx.", uID:3}, {textData:"98x Xxxxxx (xx xxxxxxxxxx)", uID:4}, {textData:"<< 98158113 >>", uID:5}, {textData:"#98158084 Xxxxx Xxxxx xxxx", uID:6}, {textData:"#98158084 Xxxxx Xxxxx xxxx", uID:7}, {textData:"Office # 98158107", uID:8}, {textData:"ID#98158087", uID:9}, {textData:"98158089", uID:10}, {textData:"00158098", uID:11}}

–全文一致で抽出
set aRes to my filterRecListByLabel1(sampleList, "textData == ’Piyomaru’")
–>  {​​​​​{​​​​​​​textData:"Piyomaru", ​​​​​​​uID:1​​​​​}​​​}

–部分一致で抽出
set bRes to my filterRecListByLabel1(sampleList, "textData contains ’Piyomaru’")
–>  {​​​​​{​​​​​​​textData:"Piyomaru", ​​​​​​​uID:1​​​​​}, ​​​​​{​​​​​​​textData:"Xx Piyomaru x", ​​​​​​​uID:2​​​​​}​​​}

–正規表現で抽出(8桁の数字)
set cRes to my filterRecListByLabel1(sampleList, "textData MATCHES ’\\\\d{8}’")
–>  {​​​​​{​​​​​​​textData:"98158089", ​​​​​​​uID:10​​​​​}, ​​​​​{​​​​​​​textData:"00158089", ​​​​​​​uID:11​​​​​}​​​}

set dRes to my filterRecListByLabel1(sampleList, "textData MATCHES ’98\\\\d{6}’")
–>  {​​​​​{​​​​​​​textData:"98158089", ​​​​​​​uID:10​​​​​}​​​}

set eRes to my filterRecListByLabel1(sampleList, "textData LIKE ’*98??????*’")
–>  {​​​​​{​​​​​​​textData:"xxxxx 11111111 98 x xxxxxxxx.", ​​​​​​​uID:3​​​​​}, ​​​​​{​​​​​​​textData:"98x Xxxxxx (xx xxxxxxxxxx)", ​​​​​​​uID:4​​​​​}, ​​​​​{​​​​​​​textData:"<< 98158113 >>", ​​​​​​​uID:5​​​​​}, ​​​​​{​​​​​​​textData:"#98158084 Xxxxx Xxxxx xxxx", ​​​​​​​uID:6​​​​​}, ​​​​​{​​​​​​​textData:"#98158084 Xxxxx Xxxxx xxxx", ​​​​​​​uID:7​​​​​}, ​​​​​{​​​​​​​textData:"Office # 98158107", ​​​​​​​uID:8​​​​​}, ​​​​​{​​​​​​​textData:"ID#98158087", ​​​​​​​uID:9​​​​​}, ​​​​​{​​​​​​​textData:"98158089", ​​​​​​​uID:10​​​​​}​​​}

set fRes to my filterRecListByLabel1(sampleList, "textData LIKE ’*\"98\"[0-9][0-9][0-9][0-9][0-9][0-9]*’") –Oops!!
–>  {}

set gRes to my filterRecListByLabel1(sampleList, "textData LIKE ’*[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*’") –Oops!!
–>  {}

set hRes to my filterRecListByLabel1(sampleList, "textData MATCHES ’.*[98]\\\\d{6}.*’") –OK!!

–>  {​​​​​{​​​​​​​textData:"<< 98158113 >>", ​​​​​​​uID:5​​​​​}, ​​​​​{​​​​​​​textData:"#98158084 Xxxxx Xxxxx xxxx", ​​​​​​​uID:6​​​​​}, ​​​​​{​​​​​​​textData:"#98158084 Xxxxx Xxxxx xxxx", ​​​​​​​uID:7​​​​​}, ​​​​​{​​​​​​​textData:"Office # 98158107", ​​​​​​​uID:8​​​​​}, ​​​​​{​​​​​​​textData:"ID#98158087", ​​​​​​​uID:9​​​​​}, ​​​​​{​​​​​​​textData:"98158089", ​​​​​​​uID:10​​​​​}​​​}

–リストに入れたレコードを、指定の属性ラベルの値で抽出
on filterRecListByLabel1(aRecList as list, aPredicate as string)
  set aArray to current application’s NSArray’s arrayWithArray:aRecList
  
set aPredicate to current application’s NSPredicate’s predicateWithFormat:aPredicate
  
set filteredArray to aArray’s filteredArrayUsingPredicate:aPredicate
  
set bList to ASify from filteredArray as list
  
return bList
end filterRecListByLabel1

★Click Here to Open This Script 

Posted in list Record | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

リストに入れたレコードを、指定の属性ラベルの値で抽出

Posted on 2月 7, 2018 by Takaaki Naganoya
AppleScript名:リストに入れたレコードを、指定の属性ラベルの値で抽出
— Created 2017-03-16 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aList to {{aLabel:"1", bLabel:"1"}, {aLabel:"2", bLabel:"2"}, {aLabel:"3", bLabel:"3"}, {aLabel:"4", bLabel:"4"}}

set anArray to current application’s NSMutableArray’s arrayWithArray:aList
set aRes to my filterRecListByLabel1(anArray, "aLabel == ’1’")
–>  {​​​​​{​​​​​​​aLabel:"1", ​​​​​​​bLabel:"1"​​​​​}​​​}

–リストに入れたレコードを、指定の属性ラベルの値で抽出
on filterRecListByLabel1(aRecList as list, aPredicate as string)
  set aArray to current application’s NSArray’s arrayWithArray:aRecList
  
set aPredicate to current application’s NSPredicate’s predicateWithFormat:aPredicate
  
set filteredArray to aArray’s filteredArrayUsingPredicate:aPredicate
  
return filteredArray as list
end filterRecListByLabel1

★Click Here to Open This Script 

Posted in list Record | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ASOCでレコードのリストから抽出

Posted on 2月 7, 2018 by Takaaki Naganoya
AppleScript名:ASOCでレコードのリストから抽出
— Created 2017-08-05 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set dList to {{deviceName:"Piyomaru AirPods", deviceAddress:"7c-04-d0-8b-bc-fb"}, {deviceName:"Takaaki Naganoya のマウス", deviceAddress:"ac-bc-32-dd-99-3e"}, {deviceName:"Takaaki Naganoya のキーボード #1", deviceAddress:"04-69-f8-be-2a-c7"}}

set dRes to filterRecListByLabel(dList, "deviceName contains ’AirPods’") of me
if dRes = {} then return false –Case: No match
set dAddr to dRes’s first item’s deviceAddress
return dAddr

–リストに入れたレコードを、指定の属性ラベルの値で抽出
on filterRecListByLabel(aRecList as list, aPredicate as string)
  –ListからNSArrayへの型変換
  
set aArray to current application’s NSArray’s arrayWithArray:aRecList
  
  
–抽出
  
set aPredicate to current application’s NSPredicate’s predicateWithFormat:aPredicate
  
set filteredArray to aArray’s filteredArrayUsingPredicate:aPredicate
  
  
–NSArrayからListに型変換して返す
  
set bList to filteredArray as list
  
return bList
end filterRecListByLabel

★Click Here to Open This Script 

Posted in list Record | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

レコードとレコードの連結

Posted on 2月 7, 2018 by Takaaki Naganoya
AppleScript名:レコードとレコードの連結
–Case: same label (fullName) and same value ("abc")
set aRec to {fullName:"abc", anAge:46}
set bRec to {fullName:"abc", aInfo:10}

set cRec to aRec & bRec
–> {fullName:"abc", anAge:46, aInfo:10}

–Case: same label (fullName) and different value ("abc", "def")
set dRec to {fullName:"abc", anAge:46}
set eRec to {fullName:"def", aInfo:10}

set fRec to dRec & eRec
–> {fullName:"abc", anAge:46, aInfo:10}

set gRec to eRec & dRec
–> {fullName:"def", aInfo:10, anAge:46}

★Click Here to Open This Script 

Posted in Record | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定ラベルと指定属性値でレコードに追加

Posted on 2月 7, 2018 by Takaaki Naganoya
AppleScript名:指定ラベルと指定属性値でレコードに追加
— Created 2017-03-16 11:51:08 +0900 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aRec to {f1:"1", f2:"2", f3:"3"}
set bRec to addValueForKey(aRec, "100", "f10") of me
–>  {​​​​​f1:"1", ​​​​​f3:"3", ​​​​​f10:"100", ​​​​​f2:"2"​​​}

on addValueForKey(aRec, aVal, aKey)
  set aDict to current application’s NSMutableDictionary’s dictionaryWithDictionary:aRec
  
aDict’s addObject:aVal forKey:aKey
  
return aDict as record
end addValueForKey

★Click Here to Open This Script 

Posted in Record | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ASOCでDict読み込みして、指定のMSの搭乗回数を取得する v2

Posted on 2月 7, 2018 by Takaaki Naganoya
AppleScript名:ASOCでDict読み込みして、指定のMSの搭乗回数を取得する v2
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aName to "efsf.plist"
set aFolName to "戦場の絆"
set aRec to retDictFromPlist(aFolName, aName) of me
set msL to msList of aRec

set eList to filterRecListByLabel(msL, "msName CONTAINS ’近 ザクII(F2) 獲得済’") of me
set aTimes to sortieTimes of first item of eList

on retDictFromPlist(aFolName, aPlistName)
  
  
set myAppSupDir to ((path to application support from user domain) as string) & aFolName & ":"
  
tell application "System Events" –Finderでなくこちらを使ってみた
    tell folder myAppSupDir
      set aExit to exists of file aPlistName
    end tell
  end tell
  
  
if aExit = false then
    return {}
  else
    set aPath to (POSIX path of myAppSupDir) & aPlistName
    
set thePath to current application’s NSString’s stringWithString:aPath
    
set thePath to thePath’s stringByExpandingTildeInPath()
    
set theDict to current application’s NSDictionary’s dictionaryWithContentsOfFile:thePath
    
return theDict as record
  end if
  
end retDictFromPlist

–リストに入れたレコードを、指定の属性ラベルの値で抽出
on filterRecListByLabel(aRecList as list, aPredicate as string)
  –ListからNSArrayへの型変換
  
set aArray to current application’s NSArray’s arrayWithArray:aRecList
  
  
–抽出
  
set aPredicate to current application’s NSPredicate’s predicateWithFormat:aPredicate
  
set filteredArray to aArray’s filteredArrayUsingPredicate:aPredicate
  
  
–NSArrayからListに型変換して返す
  
set bList to filteredArray as list
  
return bList
end filterRecListByLabel

★Click Here to Open This Script 

Posted in file list Record | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ASOCでDict書き込み_3(Bridge Plus)

Posted on 2月 7, 2018 by Takaaki Naganoya
AppleScript名:ASOCでDict書き込み_3(Bridge Plus)
use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
use script "BridgePlus" — https://www.macosxautomation.com/applescript/apps/BridgePlus.html

load framework — BridgePlus command to load

set a1List to {"msName", "sortieTimes"}
set b1List to {{"近 装甲強化型ジム 獲得済 COST: 200", 66}, {"遠 ジム・キャノン 獲得済 COST: 160", 43}, {"近 ザクII(F2) 獲得済 COST: 160", 42}, {"近 ジム・コマンド 獲得済 COST: 200", 32}, {"近 ジム(WD隊) 獲得済 COST: 160", 28}, {"近 陸戦型ガンダム 獲得済 COST: 220", 24}, {"近 ジム改 獲得済 COST: 240", 22}, {"遠 ガンタンク 獲得済 COST: 200", 22}, {"格 ジム(指揮官機) 獲得済 COST: 160", 20}, {"近 ジム 獲得済 COST: 120", 19}, {"遠 量産型ガンタンク 獲得済 COST: 160", 14}, {"格 陸戦型ジム 獲得済 COST: 120", 12}, {"格 ガンダム 獲得済 COST: 280", 11}, {"近 ジム・トレーナー 獲得済 COST: 120", 9}, {"射 ジム・スナイパーII(WD隊) 獲得済 COST: 220", 9}, {"射 陸戦型ガンダム(ジム頭) 獲得済 COST: 200", 7}, {"格 ガンダムEz8 獲得済 COST: 240", 6}, {"近 ジム・寒冷地仕様 獲得済 COST: 200", 6}, {"狙 ジム・スナイパーカスタム 獲得済 COST: 200", 6}, {"格 ジム・ストライカー 獲得済 COST: 180", 4}, {"格 ガンキャノン重装型 獲得済 COST: 160", 3}, {"近 アクア・ジム 獲得済 COST: 160", 2}, {"射 ガンキャノン 獲得済 COST: 200", 2}, {"近 ジム・コマンドライトアーマー 獲得済 COST: 160", 1}, {"格 ボールK型 獲得済 COST: 120", 0}, {"格 B.D.2号機 獲得済 COST: 260", 0}, {"格 プロトタイプガンダム 獲得済 COST: 280", 0}, {"近 パワード・ジム 獲得済 COST: 240", 0}, {"射 デザート・ジム 獲得済 COST: 160", 0}, {"遠 量産型ガンキャノン 獲得済 COST: 200", 0}}

— BridgePlus uses SMSForder instead of SMSFord in ASOBjCExtras, but method is the same
set aArray to current application’s SMSForder’s subarraysIn:b1List asDictionariesUsingLabels:a1List |error|:(missing value)

set cRec to {msList:aArray, sortieDate:date string of (current date)}

set aName to "efsf.plist"
saveRecordToFolAsPlist(cRec, "戦場の絆", aName) of me

on saveRecordToFolAsPlist(theRecord, folName, aName)
  
  
set myAppSupDir to POSIX path of (path to application support from user domain)
  
set folderURL to (current application’s class "NSURL"’s fileURLWithPath:myAppSupDir)’s URLByAppendingPathComponent:folName
  
  
–do shell script(mkdir -p)のかわりに、指定ディレクトリまで作成
  
current application’s NSFileManager’s defaultManager()’s createDirectoryAtURL:folderURL withIntermediateDirectories:true attributes:(missing value) |error|:(missing value)
  
  
set theDict to current application’s NSDictionary’s dictionaryWithDictionary:theRecord
  
set aRes to theDict’s writeToURL:(folderURL’s URLByAppendingPathComponent:aName) atomically:true
  
  
return aRes as boolean
  
end saveRecordToFolAsPlist

★Click Here to Open This Script 

Posted in file list Record | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ASOCでレコードのリストをユニーク化

Posted on 2月 7, 2018 by Takaaki Naganoya
AppleScript名:ASOCでレコードのリストをユニーク化
use AppleScript version "2.4"
use framework "Foundation"
use scripting additions

set msRecList to {{msName:"格 陸戦型ジム 獲得済 COST: 120", sortieTimes:12}, {msName:"狙 ジム・スナイパーカスタム 獲得済 COST: 200", sortieTimes:6}, {msName:"狙 ジム・スナイパーカスタム 獲得済 COST: 200", sortieTimes:6}}

set newMsList to uniquefyList(msRecList)
–>  {{sortieTimes:6, msName:"狙 ジム・スナイパーカスタム 獲得済 COST: 200"}, {sortieTimes:12, msName:"格 陸戦型ジム 獲得済 COST: 120"}}

–レコードのリストをユニーク化
on uniquefyList(aList)
  set msArray to current application’s NSArray’s arrayWithArray:aList
  
set aRes to current application’s NSSet’s setWithArray:(msArray’s allObjects())
  
set bRes to aRes’s allObjects()
  
set cRes to bRes as list
  
return cRes
end uniquefyList

★Click Here to Open This Script 

Posted in list Record | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

  • Numbersで選択範囲のセルの前後の空白を削除
  • macOS 26, Tahoe
  • macOS 15でも変化したText to Speech環境
  • KagiのWebブラウザ、Orion
  • Script Debuggerの開発と販売が2025年に終了
  • 【続報】macOS 15.5で特定ファイル名パターンのfileをaliasにcastすると100%クラッシュするバグ
  • macOS 15 リモートApple Eventsにバグ?
  • NSObjectのクラス名を取得 v2.1
  • 2024年に書いた価値あるAppleScript
  • 有害ではなくなっていたSpaces
  • macOS 15:スクリプトエディタのAppleScript用語辞書を確認できない
  • Xcode上のAppleScriptObjCのプログラムから、Xcodeのログ欄へのメッセージ出力を実行
  • (確認中)AppleScript Dropletのバグっぽい動作が解消?
  • AVSpeechSynthesizerで読み上げテスト
  • AppleScript Dropletのバグっぽい動作が「復活」(macOS 15.5β)
  • Apple、macOS標準搭載アプリ「写真」のバージョン表記を間違える
  • 指定フォルダ以下の画像のMD5チェックサムを求めて、重複しているものをピックアップ
  • macOS 26, 15.5でShortcuts.app「AppleScriptを実行」アクションのバグが修正される
  • Numbersで選択中の2列のセルを比較して並べ直して書き戻す v2
  • Script Debuggerがフリーダウンロードで提供されることに

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1391) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (204) 14.0savvy (159) 15.0savvy (156) CotEditor (66) Finder (52) Keynote (119) NSAlert (61) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (53) NSDictionary (28) NSFileManager (23) NSFont (21) NSImage (41) NSJSONSerialization (21) NSMutableArray (63) NSMutableDictionary (22) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (119) NSURL (98) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (76) Pages (56) Pixelmator Pro (20) Safari (44) Script Editor (27) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • Beginner
  • Benchmark
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • check sum
  • Clipboard
  • Cocoa-AppleScript Applet
  • Code Sign
  • Color
  • Custom Class
  • date
  • dialog
  • diff
  • drive
  • Droplet
  • 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
  • Localize
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Newt On Project
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • parallel processing
  • PDF
  • Peripheral
  • process
  • 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
  • Scripting Additions
  • 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)
  • 未分類

アーカイブ

  • 2025年10月
  • 2025年9月
  • 2025年8月
  • 2025年7月
  • 2025年6月
  • 2025年5月
  • 2025年4月
  • 2025年3月
  • 2025年2月
  • 2025年1月
  • 2024年12月
  • 2024年11月
  • 2024年10月
  • 2024年9月
  • 2024年8月
  • 2024年7月
  • 2024年6月
  • 2024年5月
  • 2024年4月
  • 2024年3月
  • 2024年2月
  • 2024年1月
  • 2023年12月
  • 2023年11月
  • 2023年10月
  • 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