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

カテゴリー: Text

GHKitのじっけん

Posted on 2月 13, 2018 by Takaaki Naganoya

–> GHKit.framework

AppleScript名:GHKitのじっけん
— Created 2016-04-12 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "GHKit" –https://github.com/gabriel/GHKit
–AppleScriptObjC uses "_" as special character (equivalent to ":" in method names). So, I changed them in whole project.
–  Original Method Name: gh_parseISO8601:
–  Converted Method Name: GHparseISO8601:

set aStr to current application’s NSString’s stringWithString:"Sun, 06 Nov 1994 08:49:37 +0000"
set aDate to (current application’s NSDate’s GHparseRFC822:aStr) as date
–>  date "1994年11月6日日曜日 17:49:37"

set bStr to current application’s NSString’s stringWithString:"1997-07-16T19:20:30.045Z"
set bDate to (current application’s NSDate’s GHparseISO8601:bStr) as date
–>  date "1997年7月17日木曜日 4:20:30"

set cDateStr to bDate’s GHformatHTTP()
–>  (NSString) "Wed, 16 Jul 1997 19:20:30 GMT"

set dDate to current application’s NSDate’s GHparseTimeSinceEpoch:(1.23456789E+9)
–>  (NSDate) 2009-02-13 23:31:30 +0000

set eDate to current application’s NSDate’s |date|()
eDate’s GHisToday() as boolean
–>  true
—–GHyesterday() cause error..

set fDate to eDate’s GHaddDays:-1
fDate’s GHwasYesterday() as boolean
–>  true

set ffRes to ((fDate’s GHtimeAgo:false)’s |description|()) as string
–> "1 day"

set anArray to current application’s NSArray’s arrayWithArray:{1, 1, 3}
set cArray to anArray’s GHuniq() as list
–>   {​​​​​1, ​​​​​3​​​}

set aDic to current application’s NSDictionary’s dictionaryWithDictionary:{key1:2, key2:3.1, key3:true}
set aJSONstr to (aDic’s GHtoJSON:(current application’s NSJSONWritingPrettyPrinted) |error|:(missing value)) as string
(*
–> (NSString) "{\n "key1" : 2,\n "key3" : true,\n "key2" : 3.1\n}"
*)

(current application’s NSString’s GHisBlank:" ") as boolean
–>  true

(current application’s NSString’s GHisBlank:(missing value)) as boolean
–>  true

set aStr to current application’s NSString’s stringWithString:" some text "
set a1Str to (aStr’s GHstrip()) as string
–> "some text"

set a2Str to (aStr’s GHpresent()) as string
–> " some text "

set a3Str to aStr’s GHreverse()
–>   " txet emos "

set a4Str to aStr’s GHcount:"e"
–> 2

★Click Here to Open This Script 

Posted in Calendar System Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Absolute Timeを取得

Posted on 2月 13, 2018 by Takaaki Naganoya
AppleScript名:Absolute Timeを取得
— Created 2016-07-12 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

–タイムスタンプ取得(Jan 1 2001 00:00:00 GMTからの相対秒、Absolute Timeで取得)
set aTime to current application’s NSString’s stringWithFormat_("%@", current application’s CFAbsoluteTimeGetCurrent()) as string
–>  "490022703.57607"

★Click Here to Open This Script 

Posted in Calendar System Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

自然言語テキストから日付を抽出

Posted on 2月 13, 2018 by Takaaki Naganoya

NSDataDetectorを用いて、自然言語テキスト(ここでは日本語のテキスト)から日付の情報を抽出するAppleScriptです。

AppleScript名:自然言語テキストから日付を抽出
— Created 2015-10-08 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.5"
use framework "Foundation"
use scripting additions

set theDate to my getDatesIn:"本テキストには次の火曜日という日付情報を含んでいる。"
log theDate
–>  date "2015年10月13日火曜日 12:00:00"

set theDate to my getDatesIn:"本テキストには今度の土曜日という日付情報を含んでいる。"
log theDate
–>  date "2015年10月10日土曜日 12:00:00"

set theDate to my getDatesIn:"昨日うな重を食べた。"
log theDate
–>  date "2015年10月7日水曜日 12:00:00"

–set theDate to my getDatesIn:"一昨日何を食べたか覚えていない。"
–>  error number -2700 No date found

–set theDate to my getDatesIn:"The day after tommorow."

–set theDate to my getDatesIn:"相対日付の認識能力は低い。明後日はいつだ?"
–>  error number -2700 No date found

–set theDate to my getDatesIn:"本テキストには元旦という日付情報を含んでいる。" –This means 1/1 in next year
–>  error number -2700 No date found

on getDatesIn:aString
  set anNSString to current application’s NSString’s stringWithString:aString
  
set theDetector to current application’s NSDataDetector’s dataDetectorWithTypes:(current application’s NSTextCheckingTypeDate) |error|:(missing value)
  
set theMatch to theDetector’s firstMatchInString:anNSString options:0 range:{0, anNSString’s |length|()}
  
if theMatch = missing value then error "No date found with String:" & aString
  
set theDate to theMatch’s |date|()
  
return theDate as date
end getDatesIn:

★Click Here to Open This Script 

Posted in Calendar System Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

GMTとの時差を求める

Posted on 2月 13, 2018 by Takaaki Naganoya
AppleScript名:GMTとの時差を求める
set tDIff to (time to GMT) / 3600
–> 9.0

★Click Here to Open This Script 

Posted in Calendar System Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

UTCTime StringとNSDateの相互変換

Posted on 2月 13, 2018 by Takaaki Naganoya
AppleScript名:UTCTime StringとNSDateの相互変換
— Created 2015-02-24 by Shane Stanley
— Changed 2015-02-25 By Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aStr to retUTCTimeString()
–>   "2018-02-13T12:40:01.936"

set aNSDate to retNSDateFromUTCString(aStr) as date
–> date "2018年2月13日火曜日 21:39:43"

–Current Date -> UTCTime String
on retUTCTimeString()
  –There is need to get Current Calendar in my Time Zone
  
set aCalendar to current application’s NSCalendar’s currentCalendar()
  
set aTimeZone to (aCalendar’s timeZone)
  
set tDiff to (aTimeZone’s secondsFromGMT())
  
  
set theNSDateFormatter to current application’s NSDateFormatter’s alloc()’s init()
  
  
theNSDateFormatter’s setDateFormat:"yyyy-MM-dd’T’HH:mm:ss.SSS"
  
theNSDateFormatter’s setTimeZone:(current application’s NSTimeZone’s timeZoneForSecondsFromGMT:tDiff)
  
  
return (theNSDateFormatter’s stringFromDate:(current application’s NSDate’s |date|())) as text
end retUTCTimeString

–UTCTime String -> NSDate
on retNSDateFromUTCString(aText)
  set aStr to current application’s NSString’s stringWithString:aText
  
  
set theNSDateFormatter to current application’s NSDateFormatter’s alloc()’s init()
  
theNSDateFormatter’s setDateFormat:"yyyy-MM-dd’T’HH:mm:ss.SSS"
  
theNSDateFormatter’s setTimeZone:(current application’s NSTimeZone’s timeZoneForSecondsFromGMT:0)
  
  
return theNSDateFormatter’s dateFromString:aStr
end retNSDateFromUTCString

★Click Here to Open This Script 

Posted in Calendar System Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ISO8601フォーマット日付のテキストをdateに変換

Posted on 2月 13, 2018 by Takaaki Naganoya
AppleScript名:ISO8601フォーマット日付のテキストをdateに変換
— Created 2015-08-28 20:19:04 +0900 by Takaaki Naganoya
— 2015 Piyomaru Software
— http://www.tondering.dk/claus/cal/iso8601.php
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use BridgePlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html

set aStr to "2010-12-01T21:35:43+09:00"
BridgePlus’s datesFromStrings:{aStr} inFormat:"yyyy-MM-dd’T’HH:mm:ssZ"
–>  {​​​​​date "2010年12月1日水曜日 21:35:43"​​​}

set aStr to "2010-12-01 21:35:43"
BridgePlus’s datesFromStrings:{aStr} inFormat:"yyyy-MM-dd HH:mm:ss"
–>  {​​​​​date "2010年12月1日水曜日 21:35:43"​​​}

★Click Here to Open This Script 

Posted in Calendar System Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ISO8601日付文字列を生成 v2

Posted on 2月 13, 2018 by Takaaki Naganoya
AppleScript名:ISO8601日付文字列を生成 v2
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

set aDate to getDateInternational(2018, 12, 18, 9, 59, 35, "CET") –―year, month, date, hour, minute, second, time zone abbreviation.
set bStr to retISO8601DateTimeString(aDate, "CET") as string
–> "2018-12-18T09:59:35+01:00"

–NSDate -> ISO8601 Date & Time String
on retISO8601DateTimeString(targDate, timeZoneAbbreviation)
  set theNSDateFormatter to current application’s NSDateFormatter’s alloc()’s init()
  
theNSDateFormatter’s setDateFormat:"yyyy-MM-dd’T’HH:mm:ssZZZZZ" — Five zeds to get a colon in the time offset (except with GMT).
  
theNSDateFormatter’s setTimeZone:(current application’s NSTimeZone’s timeZoneWithAbbreviation:(timeZoneAbbreviation))
  
return (theNSDateFormatter’s stringFromDate:targDate) as text
end retISO8601DateTimeString

–Make a GMT Date Object with parameters from a given time zone.
on getDateInternational(aYear, aMonth, aDay, anHour, aMinute, aSecond, timeZoneAbbreviation)
  set theNSCalendar to current application’s NSCalendar’s currentCalendar()
  
theNSCalendar’s setTimeZone:(current application’s NSTimeZone’s timeZoneWithAbbreviation:(timeZoneAbbreviation))
  
set theDate to theNSCalendar’s dateWithEra:1 |year|:aYear |month|:aMonth |day|:aDay hour:anHour minute:aMinute |second|:aSecond nanosecond:0
  
return theDate as date
end getDateInternational

★Click Here to Open This Script 

Posted in Calendar System Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

date objectをRFC2822 date stringに変換

Posted on 2月 13, 2018 by Takaaki Naganoya
AppleScript名:date objectをRFC2822 date stringに変換
— Created 2017-12-19 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aDate to getDateInternational(2018, 2, 1) of me
set bStr to rfc2822DateTimeString(aDate, "JST") as string
–>  "Thu, 01 Feb 2018 00:00:00 +0900"

–date -> RFC2822 Date & Time String
on rfc2822DateTimeString(targDate, timeZoneName as string)
  set theNSDateFormatter to current application’s NSDateFormatter’s alloc()’s init()
  
theNSDateFormatter’s setDateFormat:"EEE, dd MMM yyyy HH:mm:ss Z"
  
theNSDateFormatter’s setTimeZone:(current application’s NSTimeZone’s alloc()’s initWithName:timeZoneName)
  
theNSDateFormatter’s setLocale:(current application’s NSLocale’s alloc()’s initWithLocaleIdentifier:"en_US_POSIX")
  
return (theNSDateFormatter’s stringFromDate:targDate) as text
end rfc2822DateTimeString

–Make Date Object from parameters
on getDateInternational(aYear as integer, aMonth as integer, aDay as integer)
  set theNSCalendar to current application’s NSCalendar’s currentCalendar()
  
set theDate to theNSCalendar’s dateWithEra:1 |year|:aYear |month|:aMonth |day|:aDay hour:0 minute:0 |second|:0 nanosecond:0
  
return theDate as date
end getDateInternational

★Click Here to Open This Script 

Posted in Calendar System Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

RFC822エンコーダー v0

Posted on 2月 13, 2018 by Takaaki Naganoya
AppleScript名:RFC822エンコーダー v0
— Created 2016-02-07 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

set aStr to "2016-02-06 11:00:00"
set rfc822str to retRFC822StrFromDateStr(aStr) of me
–>  "Sat, 06 Feb 2016 11:00:00GMT"

on retRFC822StrFromDateObj(aObj)
  set aFormat to "yyyy-MM-dd HH:mm:ss"
  
set aTZ to "GMT"
  
set bDate to retNSDateFromStringWithTimeZone(aStr, aFormat, aTZ) of me
  
  
set aGMform to current application’s NSDateFormatter’s alloc()’s init()
  
aGMform’s setDateFormat:"EEE, dd MMM yyyy HH:mm:ss"
  
aGMform’s setTimeZone:(current application’s NSTimeZone’s timeZoneForSecondsFromGMT:0)
  
set usLocale to current application’s NSLocale’s alloc()’s initWithLocaleIdentifier:"GMT"
  
aGMform’s setLocale:usLocale
  
  
set theDate to aGMform’s stringFromDate:bDate
  
set theDate to theDate’s stringByAppendingString:"GMT"
  
return theDate as string
end retRFC822StrFromDateObj

on retRFC822StrFromDateStr(aStr)
  set aFormat to "yyyy-MM-dd HH:mm:ss"
  
set aTZ to "GMT"
  
set bDate to retNSDateFromStringWithTimeZone(aStr, aFormat, aTZ) of me
  
  
set aGMform to current application’s NSDateFormatter’s alloc()’s init()
  
aGMform’s setDateFormat:"EEE, dd MMM yyyy HH:mm:ss"
  
aGMform’s setTimeZone:(current application’s NSTimeZone’s timeZoneForSecondsFromGMT:0)
  
set usLocale to current application’s NSLocale’s alloc()’s initWithLocaleIdentifier:"GMT"
  
aGMform’s setLocale:usLocale
  
  
set theDate to aGMform’s stringFromDate:bDate
  
set theDate to theDate’s stringByAppendingString:" GMT"
  
return theDate as string
end retRFC822StrFromDateStr

on retNSDateFromStringWithTimeZone(aText, aFormat, aTZ)
  set aStr to current application’s NSString’s stringWithString:aText
  
set theNSDateFormatter to current application’s NSDateFormatter’s alloc()’s init()
  
theNSDateFormatter’s setDateFormat:(current application’s NSString’s stringWithString:aFormat)
  
theNSDateFormatter’s setTimeZone:(current application’s NSTimeZone’s timeZoneWithAbbreviation:(current application’s NSString’s stringWithString:aTZ))
  
return (theNSDateFormatter’s dateFromString:aStr) –as date
end retNSDateFromStringWithTimeZone

★Click Here to Open This Script 

Posted in System Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

RFC822デコーダー v0

Posted on 2月 13, 2018 by Takaaki Naganoya
AppleScript名:RFC822デコーダー v0
— Created 2016-02-07 by Takaaki Naganoya
— 2016 Piyomaru Software
–http://stackoverflow.com/questions/1850824/parsing-a-rfc-822-date-with-nsdateformatter
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set dateString to "Sun, 19 May 2002 15:21:36 GMT"
–set dateString to "Tue, 01 Dec 2009 08:48:25 +0000"

set aRes to rfc822StrDecode(dateString) of me
–> date "2002年5月20日月曜日 0:21:36"

–http://stackoverflow.com/questions/1850824/parsing-a-rfc-822-date-with-nsdateformatter
on rfc822StrDecode(dateString)
  set aTZ to "GMT"
  
set en_US_POSIX to current application’s NSLocale’s alloc()’s initWithLocaleIdentifier:"en_US_POSIX"
  
set dateFormatter to current application’s NSDateFormatter’s alloc()’s init()
  
dateFormatter’s setLocale:en_US_POSIX
  
dateFormatter’s setTimeZone:(current application’s NSTimeZone’s timeZoneWithAbbreviation:(current application’s NSString’s stringWithString:aTZ))
  
  
set aDate to missing value
  
set RFC822String to (current application’s NSString’s stringWithString:dateString)’s uppercaseString()
  
if (RFC822String’s rangeOfString:",")’s location() is not equal to (current application’s NSNotFound) then
    if aDate is equal to missing value then
      — Sun, 19 May 2002 15:21:36 GMT
      
dateFormatter’s setDateFormat:"EEE, d MMM yyyy HH:mm:ss zzz"
      
set aDate to dateFormatter’s dateFromString:RFC822String
    end if
    
    
if aDate is equal to missing value then
      — Sun, 19 May 2002 15:21 GMT
      
dateFormatter’s setDateFormat:"EEE, d MMM yyyy HH:mm zzz"
      
set aDate to dateFormatter’s dateFromString:RFC822String
    end if
    
    
if aDate is equal to missing value then
      — Sun, 19 May 2002 15:21:36
      
dateFormatter’s setDateFormat:"EEE, d MMM yyyy HH:mm:ss"
      
set aDate to dateFormatter’s dateFromString:RFC822String
    end if
    
    
if aDate is equal to missing value then
      — Sun, 19 May 2002 15:21:36
      
dateFormatter’s setDateFormat:"EEE, d MMM yyyy HH:mm"
      
set aDate to dateFormatter’s dateFromString:RFC822String
    end if
  else
    if aDate is equal to missing value then
      — 19 May 2002 15:21:36 GMT
      
dateFormatter’s setDateFormat:"d MMM yyyy HH:mm:ss zzz"
      
set aDate to dateFormatter’s dateFromString:RFC822String
    end if
    
    
if aDate is equal to missing value then
      — 19 May 2002 15:21 GMT
      
dateFormatter’s setDateFormat:"d MMM yyyy HH:mm zzz"
      
set aDate to dateFormatter’s dateFromString:RFC822String
    end if
    
    
if aDate is equal to missing value then
      — 19 May 2002 15:21:36
      
dateFormatter’s setDateFormat:"d MMM yyyy HH:mm:ss"
      
set aDate to dateFormatter’s dateFromString:RFC822String
    end if
    
    
if aDate is equal to missing value then
      — 19 May 2002 15:21
      
dateFormatter’s setDateFormat:"d MMM yyyy HH:mm"
      
set aDate to dateFormatter’s dateFromString:RFC822String
    end if
    
  end if
  
  
if aDate is equal to missing value then return false
  
return aDate as date
end rfc822StrDecode

★Click Here to Open This Script 

Posted in System Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

画像を文字認識して文字エリアを塗りつぶし v3

Posted on 2月 11, 2018 by Takaaki Naganoya


▲Original Image


▲Filtered Image(CIColorMonochrome)


▲Filtered Image(CIColorPosterize)


▲Result Image

AppleScript名:画像を文字認識して文字エリアを塗りつぶし v3
— Created 2017-11-19 by Takaaki Naganoya
— Modified 2018-02-11 by Takaaki Naganoya
–v3:画像の前処理を付加
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "QuartzCore"
use framework "AppKit"

set retinaF to (current application’s NSScreen’s mainScreen()’s backingScaleFactor()) as real
–>  2.0 (Retina) / 1.0 (Non Retina)

set imgPath to POSIX path of (choose file of type {"public.image"})
set anImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:imgPath
set aCIImage to convNSImageToCIimage(anImage)

–モノクロ化フィルタ
set bCIImage to monochromefilterACGImage(aCIImage) of me

–2階調ポスタライズフィルタ
set cCIImage to posterizefilterACGImage(bCIImage) of me

–文字領域認識
set detectList to textDetect(cCIImage) of me

–描画開始
anImage’s lockFocus()

repeat with i in detectList
  set origX to (x of origin of i) / retinaF
  
set origY to (y of origin of i) / retinaF
  
set sizeX to (width of |size| of i) / retinaF
  
set sizeY to (height of |size| of i) / retinaF
  
  
set theRect to {{x:origX, y:origY}, {width:sizeX, height:sizeY}}
  
  
set theNSBezierPath to current application’s NSBezierPath’s bezierPath
  (
theNSBezierPath’s appendBezierPathWithRect:theRect)
  
  
set rRnd to (random number from 1 to 10) / 10
  
set gRnd to (random number from 1 to 10) / 10
  
set bRnd to (random number from 1 to 10) / 10
  
set fillColor to (current application’s NSColor’s colorWithCalibratedRed:rRnd green:gRnd blue:bRnd alpha:0.6)
  
  
fillColor’s |set|() –色設定
  
theNSBezierPath’s fill() –ぬりつぶし
end repeat

anImage’s unlockFocus()
–描画ここまで

set aUUIDstr to (current application’s NSUUID’s UUID()’s UUIDString()) as string
set aPath to ((current application’s NSString’s stringWithString:imgPath)’s stringByDeletingLastPathComponent()’s stringByAppendingPathComponent:aUUIDstr)’s stringByAppendingPathExtension:"png"

set fRes to saveImageRepAtPathAsPNG(anImage, aPath) of me

on openImageFile(imageFile) — imageFile: POSIX path 形式のファイルパス
  set fileURL to current application’s |NSURL|’s fileURLWithPath:imageFile
  
return current application’s CIImage’s alloc()’s initWithContentsOfURL:fileURL
end openImageFile

–画像を指定パスにPNG形式で保存
on saveImageRepAtPathAsPNG(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep
  
  
–書き出しファイルパス情報を作成
  
set pathString to current application’s NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
  
–書き出し
  
set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value))
  
return (myNewImageData’s writeToFile:newPath atomically:true) as boolean
end saveImageRepAtPathAsPNG

on textDetect(imageRef)
  — 検出器のオプションを NSDictonary で作成
  
set optDic1 to current application’s NSDictionary’s dictionaryWithObject:(current application’s CIDetectorAccuracyHigh) forKey:(current application’s CIDetectorAccuracy)
  
set textDetector to current application’s CIDetector’s detectorOfType:(current application’s CIDetectorTypeText) context:(missing value) options:optDic1
  
  
— 文字エリア検出を実行
  
set optDic2 to current application’s NSDictionary’s dictionaryWithObject:true forKey:(current application’s CIDetectorReturnSubFeatures)
  
set textArray to textDetector’s featuresInImage:imageRef options:optDic2
  
  
set fList to {}
  
  
— 検出されたテキストの位置とサイズをログに出力
  
repeat with i from 1 to (count of textArray)
    set typeFace to item i of textArray
    
set bList to (typeFace’s subFeatures())
    
    
repeat with ii in bList
      set aBounds to ii’s |bounds|()
      
set aType to ii’s type()
      
set the end of fList to aBounds
    end repeat
    
  end repeat
  
  
return fList
  
end textDetect

on convCIimageToNSImage(aCIImage)
  set aRep to current application’s NSBitmapImageRep’s alloc()’s initWithCIImage:aCIImage
  
set tmpSize to aRep’s |size|()
  
set newImg to current application’s NSImage’s alloc()’s initWithSize:tmpSize
  
newImg’s addRepresentation:aRep
  
return newImg
end convCIimageToNSImage

on convNSImageToCIimage(aNSImage)
  set tiffDat to aNSImage’s TIFFRepresentation()
  
set aRep to current application’s NSBitmapImageRep’s imageRepWithData:tiffDat
  
set newImg to current application’s CIImage’s alloc()’s initWithBitmapImageRep:aRep
  
return newImg
end convNSImageToCIimage

–Posterizeフィルタ
on posterizefilterACGImage(aCIImage)
  set aFilter to current application’s CIFilter’s filterWithName:"CIColorPosterize"
  
aFilter’s setDefaults()
  
  
aFilter’s setValue:aCIImage forKey:"inputImage"
  
aFilter’s setValue:2 forKey:"inputLevels"
  
  
set aOutImage to aFilter’s valueForKey:"outputImage"
  
return aOutImage
end posterizefilterACGImage

–Monochromeフィルタ
on monochromefilterACGImage(aCIImage)
  set aFilter to current application’s CIFilter’s filterWithName:"CIColorMonochrome"
  
aFilter’s setDefaults()
  
  
aFilter’s setValue:aCIImage forKey:"inputImage"
  
aFilter’s setValue:1.0 forKey:"inputIntensity"
  
  
set aOutImage to aFilter’s valueForKey:"outputImage"
  
return aOutImage
end monochromefilterACGImage

★Click Here to Open This Script 

Posted in file Image Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

RTF本文内の色を置換 v2

Posted on 2月 11, 2018 by Takaaki Naganoya

指定のRTF書類の本文中の色を置換するAppleScriptです。

指定のRTF書類内のカラーをざっくりとした色に分類し、同じくざっくりとした色名で置換対象を指定し(blue, green)、指定色(black)に色置換。結果をデスクトップ上に別名で保存します。

AppleScript名:RTF本文内の色を置換 v2
— Created 2018-01-13 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSData : a reference to current application’s NSData
property NSUUID : a reference to current application’s NSUUID
property NSColor : a reference to current application’s NSColor
property NSString : a reference to current application’s NSString
property NSPredicate : a reference to current application’s NSPredicate
property NSDictionary : a reference to current application’s NSDictionary
property NSMutableArray : a reference to current application’s NSMutableArray
property NSMutableAttributedString : a reference to current application’s NSMutableAttributedString
property NSForegroundColorAttributeName : a reference to current application’s NSForegroundColorAttributeName
property NSDocumentTypeDocumentAttribute : a reference to current application’s NSDocumentTypeDocumentAttribute

set targFilePath to POSIX path of (choose file of type {"public.rtf"})
set targColorNameList to {"blue", "green"} –replace target color names
set toColor to NSColor’s blackColor() –to color
set aRes to replaceRTFColorsByColorName(targFilePath, targColorNameList, toColor, 65535) of me

–指定RTF書類本文中、名称で指定した色の該当箇所を指定色(NSColor)に置換する(複数色)
on replaceRTFColorsByColorName(targFilePath as string, targColorNameList as list, toColor, aColorMax as integer)
  script spd
    property hitList : {}
  end script
  
  
set (hitList of spd) to {}
  
set aFilePath to NSString’s stringWithString:(targFilePath)
  
set aData to NSData’s dataWithContentsOfFile:aFilePath options:0 |error|:(missing value)
  
set theStyledText to NSMutableAttributedString’s alloc()’s initWithData:aData options:(missing value) documentAttributes:(missing value) |error|:(missing value)
  
  
set attrList to getAttributeRunsFromAttrString(theStyledText, aColorMax) of me
  
set attrArray to NSMutableArray’s arrayWithArray:attrList
  
  
theStyledText’s beginEditing() ——
  
repeat with ii in targColorNameList
    set jj to contents of ii
    
set thePred to NSPredicate’s predicateWithFormat_("colorName == %@", jj)
    
set (hitList of spd) to ((attrArray’s filteredArrayUsingPredicate:thePred)’s valueForKey:"rangeVal") as list
    
    
repeat with i in (hitList of spd)
      (theStyledText’s addAttribute:(NSForegroundColorAttributeName) value:toColor range:(contents of i))
    end repeat
    
  end repeat
  
theStyledText’s endEditing() ——
  
  
–Save RTF to desktop
  
set targFol to current application’s NSHomeDirectory()’s stringByAppendingPathComponent:"Desktop"
  
set aRes to saveStyledTextAsRTF(targFol, theStyledText) of me
  
return aRes as boolean
end replaceRTFColorsByColorName

–AttributedStringを書式でlist of record化
on getAttributeRunsFromAttrString(theStyledText, aColorMax)
  script aSpd
    property styleList : {}
  end script
  
  
set (styleList of aSpd) to {} —for output
  
  
set thePureString to theStyledText’s |string|() –pure string from theStyledText
  
  
set theLength to theStyledText’s |length|()
  
set startIndex to 0
  
  
repeat until (startIndex = theLength)
    set {theAtts, theRange} to theStyledText’s attributesAtIndex:startIndex longestEffectiveRange:(reference) inRange:{startIndex, theLength – startIndex}
    
    
–String
    
set aText to (thePureString’s substringWithRange:theRange) as string
    
    
–Color
    
set aColor to (theAtts’s valueForKeyPath:"NSColor")
    
if aColor is not equal to missing value then
      set aSpace to aColor’s colorSpace()
      
      
set aRed to (aColor’s redComponent()) * aColorMax
      
set aGreen to (aColor’s greenComponent()) * aColorMax
      
set aBlue to (aColor’s blueComponent()) * aColorMax
      
      
set colList to {aRed as integer, aGreen as integer, aBlue as integer} –for comparison
      
set colStrForFind to (aRed as integer as string) & " " & (aGreen as integer as string) & " " & (aBlue as integer as string) –for filtering
    else
      set colList to {0, 0, 0}
      
set colStrForFind to "0 0 0"
    end if
    
    
–Color Name
    
set cName to retColorName(aRed, aGreen, aBlue, aColorMax) of me
    
    
–Font
    
set aFont to (theAtts’s valueForKeyPath:"NSFont")
    
if aFont is not equal to missing value then
      set aDFontName to aFont’s displayName()
      
set aDFontSize to aFont’s pointSize()
    end if
    
    
set the end of (styleList of aSpd) to {stringVal:aText, colorStr:colStrForFind, colorVal:colList, fontName:aDFontName as string, fontSize:aDFontSize, rangeVal:theRange, colorName:cName}
    
    
set startIndex to current application’s NSMaxRange(theRange)
    
  end repeat
  
  
return (styleList of aSpd)
end getAttributeRunsFromAttrString

–RGB値から色名称(だいたいの色)を計算する
on retColorName(rCol as integer, gCol as integer, bCol as integer, aColMax as integer)
  set aCol to makeNSColorFromRGBAval(rCol, gCol, bCol, aColMax, aColMax) of me
  
set hueVal to aCol’s hueComponent() as real
  
set satVal to aCol’s saturationComponent() as real
  
set brightVal to aCol’s brightnessComponent() as real
  
  
if satVal ≤ 0.01 then set satVal to 0.0
  
  
if satVal = 0.0 then
    if brightVal ≤ 0.2 then
      set colName to "black"
    else if (brightVal > 0.95) then
      set colName to "white"
    else
      set colName to "gray"
    end if
  else
    if hueVal ≤ (15.0 / 360) or hueVal ≥ (330 / 360) then
      set colName to "red"
    else if hueVal ≤ (45.0 / 360) then
      set colName to "orange"
    else if hueVal < (70.0 / 360) then
      set colName to "yellow"
    else if hueVal < (150.0 / 360) then
      set colName to "green"
    else if hueVal < (190.0 / 360) then
      set colName to "cyan"
    else if (hueVal < 250.0 / 360.0) then
      set colName to "blue"
    else if (hueVal < 290.0 / 360.0) then
      set colName to "purple"
    else
      set colName to "magenta"
    end if
  end if
  
  
return colName
end retColorName

on makeNSColorFromRGBAval(redValue as integer, greenValue as integer, blueValue as integer, alphaValue as integer, aMaxVal as integer)
  set aRedCocoa to (redValue / aMaxVal) as real
  
set aGreenCocoa to (greenValue / aMaxVal) as real
  
set aBlueCocoa to (blueValue / aMaxVal) as real
  
set aAlphaCocoa to (alphaValue / aMaxVal) as real
  
set aColor to NSColor’s colorWithCalibratedRed:aRedCocoa green:aGreenCocoa blue:aBlueCocoa alpha:aAlphaCocoa
  
return aColor
end makeNSColorFromRGBAval

–スタイル付きテキストを指定フォルダ(POSIX path)にRTFで書き出し
on saveStyledTextAsRTF(targFol, aStyledString)
  set bstyledLength to aStyledString’s |string|()’s |length|()
  
set bDict to NSDictionary’s dictionaryWithObject:"NSRTFTextDocumentType" forKey:(NSDocumentTypeDocumentAttribute)
  
set bRTF to aStyledString’s RTFFromRange:(current application’s NSMakeRange(0, bstyledLength)) documentAttributes:bDict
  
  
set theName to (NSUUID’s UUID()’s UUIDString())
  
set thePath to NSString’s stringWithString:targFol
  
set thePath to (thePath’s stringByAppendingPathComponent:theName)’s stringByAppendingPathExtension:"rtf"
  
return (bRTF’s writeToFile:thePath atomically:true) as boolean
end saveStyledTextAsRTF

★Click Here to Open This Script 

Posted in Color RTF Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

rtf_rtfdからテキスト抽出

Posted on 2月 11, 2018 by Takaaki Naganoya

RTFないしRTFD(添付ファイルつきRTF)からテキストを抽出するAppleScriptです。

AppleScript名:rtf_rtfdからテキスト抽出
— Created 2018-02-10 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set aFile to choose file of type {"com.apple.rtfd", "public.rtf"}
set aRes to retTextFromRTF(aFile) of me

on retTextFromRTF(aFile)
  set aFilePath to current application’s NSString’s stringWithString:(POSIX path of aFile)
  
set anExt to (aFilePath’s pathExtension()) as string
  
if anExt = "rtfd" then
    set aFilePath to aFilePath’s stringByAppendingString:"TXT.rtf"
  end if
  
  set aData to current application’s NSData’s dataWithContentsOfFile:aFilePath options:0 |error|:(missing value)
  
set theStyledText to current application’s NSMutableAttributedString’s alloc()’s initWithData:aData options:(missing value) documentAttributes:(missing value) |error|:(missing value)
  
  if theStyledText is not equal to missing value then
    return (theStyledText’s |string|()) as string
  else
    return false –Not RTF file
  end if
end retTextFromRTF

★Click Here to Open This Script 

Posted in file RTF Text | Tagged 10.11savvy 10.12savvy 10.13savvy | 1 Comment

指定URLをロードしてtitleを取得

Posted on 2月 11, 2018 by Takaaki Naganoya
AppleScript名:指定URLをロードしてtitleを取得
— Created 2015-09-07 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "WebKit"

property loadDone : false
property theWebView : missing value

set aURL to "https://www.youtube.com/watch?v=WuziqYptTyE"
set aTitle to getPageTitle(aURL)
–>  "戦場の絆ポータブル【HD】鉱山都市 オンライン対戦 2015.09.04 – YouTube"

on getPageTitle(aURL)
  –Check If this script runs in foreground
  
if not (current application’s NSThread’s isMainThread()) as boolean then
    display alert "This script must be run from the main thread (Command-Control-R in Script Editor)." buttons {"Cancel"} as critical
    
error number -128
  end if
  
  
set my loadDone to false
  
set my theWebView to missing value
  
openURL(aURL)
  
  
set waitLoop to 1000 * 60 –60 seconds
  
  
set hitF to false
  
repeat waitLoop times
    if my loadDone = true then
      set hitF to true
      
exit repeat
    end if
    
current application’s NSThread’s sleepForTimeInterval:("0.001" as real) –delay 0.001
  end repeat
  
if hitF = false then return
  
  
set jsText to "document.title"
  
set x to ((my theWebView)’s stringByEvaluatingJavaScriptFromString:jsText) as text
  
set my theWebView to missing value
  
  
return x
end getPageTitle

–WebViewにURLを読み込む
on openURL(aURL)
  set noter1 to current application’s NSNotificationCenter’s defaultCenter()
  
set my theWebView to current application’s WebView’s alloc()’s init()
  
noter1’s addObserver:me selector:"webLoaded:" |name|:(current application’s WebViewProgressFinishedNotification) object:(my theWebView)
  
my (theWebView’s setMainFrameURL:aURL)
end openURL

–Web Viewのローディング完了時に実行
on webLoaded:aNotification
  set my loadDone to true
end webLoaded:

★Click Here to Open This Script 

Posted in Internet JavaScript Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

URLの妥当性チェック

Posted on 2月 11, 2018 by Takaaki Naganoya
AppleScript名:URLの妥当性チェック
— Created 2015-09-06 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
–http://stackoverflow.com/questions/1471201/how-to-validate-an-url-on-the-iphone

set aRes1 to validateURL("http://www.apple.com/jp")
–>  true

set aRes2 to validateURL("http.s://www.gmail.com")
–>  false
set aRes3 to validateURL("https:.//gmailcom")
–>  false
set aRes4 to validateURL("https://gmail.me.")
–>  false
set aRes5 to validateURL("https://www.gmail.me.com.com.com.com")
–>  true
set aRes6 to validateURL("http:/./ww-w.wowone.com")
–>  false
set aRes7 to validateURL("http://.www.wowone")
–>  false
set aRes8 to validateURL("http://www.wow-one.com")
–>  true
set aRes9 to validateURL("http://www.wow_one.com")
–>  true
set aRes10 to validateURL("http://.")
–>  false
set aRes11 to validateURL("http://")
–>  false
set aRes12 to validateURL("http://k")
–>  false

return {aRes2, aRes3, aRes4, aRes5, aRes6, aRes7, aRes8, aRes9, aRes10, aRes11, aRes12}
–>  {​​​​​false, ​​​​​false, ​​​​​false, ​​​​​true, ​​​​​false, ​​​​​false, ​​​​​true, ​​​​​true, ​​​​​false, ​​​​​false, ​​​​​false​​​}

–URLの妥当性チェック
on validateURL(anURL as text)
  –set regEx1 to current application’s NSString’s stringWithString:"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+"
  
set regEx1 to current application’s NSString’s stringWithString:"((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"
  
set predicate1 to current application’s NSPredicate’s predicateWithFormat_("SELF MATCHES %@", regEx1)
  
set aPredRes1 to (predicate1’s evaluateWithObject:anURL) as boolean
  
return aPredRes1
end validateURL

★Click Here to Open This Script 

Posted in Internet regexp Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

画像にステガノグラフィーで埋め込まれた文字列を取り出す

Posted on 2月 9, 2018 by Takaaki Naganoya

オープンソースのステガノグラフィーのプログラム「ISStego」(By Isaac Stevao Sena氏)を用いて、JPEG画像に埋め込んだ文字情報を取り出すAppleScriptです。

ISStegoは普通にObjective-Cで書かれたGUIベースのアプリケーションだったので、そのままではAppleScriptから呼び出せませんでした。

そこで、中身をそのままそっくり移し替えた新規フレームワーク「stegLib.framework」をでっちあげてビルドし、AppleScriptから呼び出してみました。

JPEG画像にUTF-8の文字情報(日本語文字列)を埋め込んで別のPNG画像に書き出し、書き出した画像からUTF-8の文字情報を取り出す実験を行ってみました。エンコードもデコードもうまく行っているようなので、うまく処理できていると思います。

ステガノグラフィーについて初めて聞いたのは20年ぐらい前のことと記憶していますが、こんなに手軽に使えるようになっていたとは驚きです。


▲Original Image


▲Information Embedded Image

–> stegLib.framework

AppleScript名:画像にステガノグラフィーで埋め込まれた文字列を取り出す
— Created 2015-10-21 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "stegLib" –https://github.com/isena/ISStego

set aFile to POSIX path of (choose file of type {"public.png"})
set aFilePath to current application’s NSString’s stringWithString:aFile
set aURL to current application’s |NSURL|’s fileURLWithPath:aFilePath
set aImage to current application’s NSImage’s alloc()’s initWithContentsOfURL:aURL

set aDecodedData to current application’s ISStegoDecoder’s alloc()’s init()’s decodeStegoImage:aImage |error|:(missing value)
set resStr to (current application’s NSString’s alloc()’s initWithData:aDecodedData encoding:(current application’s NSUTF8StringEncoding)) as string
–> "長野谷隆昌/ぴよまるソフトウェア/Piyomaru Software"

★Click Here to Open This Script 

Posted in file Image Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

画像にステガノグラフィーで情報を埋め込む

Posted on 2月 9, 2018 by Takaaki Naganoya

オープンソースのステガノグラフィー(steganography)のプログラム「ISStego」(By Isaac Stevao Sena氏)を用いて、JPEG画像に文字情報を埋め込むAppleScriptです。

ISStegoは普通にObjective-Cで書かれたGUIベースのアプリケーションだったので、そのままではAppleScriptから呼び出せませんでした。

そこで、中身をそのままそっくり移し替えた新規フレームワーク「stegLib.framework」をでっちあげてビルドし、AppleScriptから呼び出してみました。

JPEG画像にUTF-8の文字情報(日本語文字列)を埋め込んで別のPNG画像に書き出し、書き出した画像からUTF-8の文字情報を取り出す実験を行ってみました。エンコードもデコードもうまく行っているようなので、うまく処理できていると思います。

ステガノグラフィー(steganography)について初めて聞いたのは20年ぐらい前のことと記憶していますが、こんなに手軽に使えるようになっていたとは驚きです。

Twitterにプログラムを投稿するのに、(140文字制限を回避するため)文字を画像化して投稿しているのを見て、「そこまでやるなら、画像にプログラムの文字データを埋め込めばいいのに」と思い、「ステガノグラフィーで埋め込めばいいんじゃないか?」ということで、埋め込めるようになったのですが、肝心のTwitterクライアントから画像をダウンロードする手段がなかったのがダメダメでした(Webブラウザ経由ならOKです)。


▲Original Image


▲Information Embedded Image

–> stegLib.framework

AppleScript名:画像にステガノグラフィーで情報を埋め込む
— Created 2015-10-21 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "stegLib" –https://github.com/isena/ISStego

set aFile to POSIX path of (choose file of type {"public.jpeg"})
set encString to "長野谷隆昌/ぴよまるソフトウェア/Piyomaru Software"

set aFilePath to current application’s NSString’s stringWithString:aFile
set aExt to "png"

set newPath to aFilePath’s stringByDeletingPathExtension()
set newPath2 to newPath’s stringByAppendingString:"_stego"
set newPath3 to newPath2’s stringByAppendingPathExtension:aExt

set aURL to current application’s |NSURL|’s fileURLWithPath:aFilePath
set aImage to current application’s NSImage’s alloc()’s initWithContentsOfURL:aURL
set strData to current application’s NSString’s stringWithString:encString

set aEncimage to current application’s ISStegoEncoder’s alloc()’s init()’s stegoImageForImage:aImage |data|:strData |error|:(missing value)
my saveImageRepAtPathAsPNG(aEncimage, newPath3)

–画像を指定パスにPNG形式で保存
on saveImageRepAtPathAsPNG(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to current application’s NSBitmapImageRep’s imageRepWithData:imageRep
  
  
set pathString to current application’s NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
  
set myNewImageData to (aRawimg’s representationUsingType:(current application’s NSPNGFileType) |properties|:(missing value))
  
return (myNewImageData’s writeToFile:newPath atomically:true) as boolean
end saveImageRepAtPathAsPNG

★Click Here to Open This Script 

Posted in file Image Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Camel Case化

Posted on 2月 8, 2018 by Takaaki Naganoya
AppleScript名:Camel Case化
— Created 2015-12-24 by Shane Stanley
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

camelCase("this is a pen") of me
–>  "thisIsAPen."

on camelCase(aPhrase)
  set firstWord to current application’s NSString’s stringWithString:(word 1 of aPhrase)
  
set firstWord to firstWord’s |lowercaseString|()
  
set restOfPhrase to current application’s NSString’s stringWithString:(text from word 2 to -1 of aPhrase)
  
set restOfPhrase to restOfPhrase’s capitalizedString()’s stringByReplacingOccurrencesOfString:space withString:""
  
set newPhrase to firstWord’s stringByAppendingString:restOfPhrase
  
return (newPhrase’s stringByFoldingWithOptions:(current application’s NSDiacriticInsensitiveSearch) locale:(missing value)) as text
end camelCase

★Click Here to Open This Script 

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

文字エンコーディングを自動判別してファイル読み込み v1.2.1

Posted on 2月 8, 2018 by Takaaki Naganoya

指定のテキストファイル(日本語テキストを想定)を、文字エンコーディングを自動判定して読み込むAppleScriptです。

これまで、日本語テキストファイルの文字エンコーディングを自動判定するのにテキストエディタをAppleScriptからコントロールして使っていましたが、それだと並列処理するAppleScriptの中で使用できないし、テキストエディタがない環境では実行することができません(ダウンロードすればいいだけの話ですが)。

さまざまな日本語テキストエディタのソースコードをながめて、文字コードの自動判定ロジックがわかってきたので、AppleScriptで実装してみました。さらに、独自の「文字化け判定ロジック」を考えたので、それを併用しています。

Step 1 伝統的な判定(勝ち抜け方式)

伝統的な文字コードの判定を順次行います。この、判定を行う順序が重要です。最初にISO2022JPのチェック、ついでEUC、UTF-8、シフトJISと、順次コード判定を行います。勝ち抜け方式で、妥当な文字エンコーディングとみなしたらそこで評価を打ち切ります。

Step 2 総当たり判定(全部評価してから考える)

UTF-16BE/LE/無印Unicodeについては、それぞれの文字エンコーディングで実際に評価してみて、文字化けしないものを採用します。独自ロジックにより文字化け状態をプログラム的に判断するのと、そのエンコーディングで読み込んだ結果をNSLinguisticTaggerで評価し、「ja」(日本語)と判定するかどうかの確認をすべてのエンコーディングで行なっています。

以上の2ステップでだいたい日本語テキストのエンコーディング自動判定ができています。

もし、寿司屋の湯のみ茶碗のように漢字で魚の名前を羅列した日本語テキストがUTF-16BEとかで書かれていたりすると自動判定できない可能性もありますが、青空文庫の日本語テキストやWebに掲載されているテクニカルな記事(アルファベットやカタカナの使用比率が高い)でテストしてみたところ、問題なく判定できています(実際に魚の名前のテキストを作って読み込んでみましたが、とくに問題はありませんでした)。

だいたい、日本語として意味をなしているようなテキストであれば、文字コードの自動判定はできているように思います。ただ、世間は広いので、本Scriptのロジックで判定できないようなケースもあるかもしれません。そのような時にはコメント欄やフォーラムへの報告をお願いいたします(対応するかどうかは別として。知り合いのテキストエディタ作者の方は、無償で公開しているソフトに文句を言われて「すぐに対応しろ!」だのと散々言われたそうで、、、、、、、)。

AppleScript名:文字エンコーディングを自動判別してファイル読み込み v1.2.1
— Created 2014-12-28 by Takaaki Naganoya
— Modified 2014-12-29 by Shane Stanley
— Modified 2015-10-03 by Takaaki Naganoya
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

set aPath to POSIX path of (choose file)
set aRes to readJapanesTextFileWithGuessingEncoding(aPath) of me
set bRes to aRes as string

–Read Japanese text with detecting its text encoding
on readJapanesTextFileWithGuessingEncoding(aPOSIXpath as string)
  
  
–ISO2022JP check
  
set aNSData to current application’s NSData’s dataWithContentsOfFile:aPOSIXpath
  
set aDataLength to aNSData’s |length|()
  
if aDataLength > 1024 then set aDataLength to 1024
  
  
–0x1B check
  
set anNSString to current application’s NSString’s stringWithString:(character id 27) — 0x1B
  
set theData to anNSString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set theRange to aNSData’s rangeOfData:theData options:0 range:(current application’s NSMakeRange(0, aDataLength))
  
  
–found 0x1B in aNSData
  
if |length| of theRange = 1 and location of theRange < aDataLength then
    set aStr to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSISO2022JPStringEncoding)) –21
    
if aStr is not equal to missing value then return (aStr as text) — ISO2022JP
  end if
  
  
–EUC
  
set resValue to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSJapaneseEUCStringEncoding))
  
–log resValue
  
if resValue is not equal to missing value then return (resValue as text)
  
–UTF-8
  
set resValue to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSUTF8StringEncoding))
  
–log resValue
  
if resValue is not equal to missing value then return (resValue as text)
  
–SHift JIS
  
set resValue to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSShiftJISStringEncoding))
  
–log resValue
  
if resValue is not equal to missing value then return (resValue as text)
  
  
  
–UTF-16BE/LE/無印Unicodeは多数決を取る
  
set resValue1 to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSUTF16BigEndianStringEncoding)) as text
  
–log resValue1
  
set sample1 to getTextSample(resValue1) of me
  
set lang1 to specifyLanguageOfText(sample1) of me
  
set para1 to length of (paragraphs of sample1)
  
set words1 to length of (words of sample1)
  
  
set resValue2 to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSUTF16LittleEndianStringEncoding)) as text
  
–log resValue2
  
set sample2 to getTextSample(resValue2) of me
  
set lang2 to specifyLanguageOfText(sample2) of me
  
set para2 to length of (paragraphs of sample2)
  
set words2 to length of (words of sample2)
  
  
set resValue3 to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSUnicodeStringEncoding)) as text
  
–log resValue3
  
set sample3 to getTextSample(resValue3) of me
  
set lang3 to specifyLanguageOfText(sample3) of me
  
set para3 to length of (paragraphs of sample3)
  
set words3 to length of (words of sample3)
  
  
–文字および文法的に見て「日本語」ならそれを返す
  
if lang1 = "ja" then return resValue1
  
if lang2 = "ja" then return resValue2
  
if lang3 = "ja" then return resValue2
  
  
  
–文字化けしたときには、日本語の「Word」として認識されづらく、Paragraphも少ない(1とか)なので条件で除外する
  
if para1 is not equal to 1 then
    if (words1 ≤ words2) or (words1 ≤ words3) then
      return resValue1
    end if
  end if
  
  
if para2 is not equal to 1 then
    if (words2 ≤ words1) or (words2 ≤ words3) then
      return resValue2
    end if
  end if
  
  
if para3 is not equal to 1 then
    if (words3 ≤ words1) or (words3 ≤ words2) then
      return resValue3
    end if
  end if
  
  
return false
  
  
(*
  –おまけ(未確認)
  set resValue to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSWindowsCP1251StringEncoding))
  if resValue is not equal to missing value then return resValue
  
  set resValue to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSWindowsCP1252StringEncoding))
  if resValue is not equal to missing value then return resValue
  
  set resValue to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSWindowsCP1253StringEncoding))
  if resValue is not equal to missing value then return resValue
  
  set resValue to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSWindowsCP1254StringEncoding))
  if resValue is not equal to missing value then return resValue
  
  set resValue to (current application’s NSString’s alloc()’s initWithData:aNSData encoding:(current application’s NSWindowsCP1250StringEncoding))
  if resValue is not equal to missing value then return resValue
  
  return false
  *)

end readJapanesTextFileWithGuessingEncoding

on specifyLanguageOfText(aStr)
  set aNSstring to current application’s NSString’s stringWithString:aStr
  
set tagSchemes to current application’s NSArray’s arrayWithObjects:(current application’s NSLinguisticTagSchemeLanguage)
  
set tagger to current application’s NSLinguisticTagger’s alloc()’s initWithTagSchemes:tagSchemes options:0
  
tagger’s setString:aNSstring
  
set aLanguage to tagger’s tagAtIndex:0 |scheme|:(current application’s NSLinguisticTagSchemeLanguage) tokenRange:(missing value) sentenceRange:(missing value)
  
return aLanguage as text
end specifyLanguageOfText

on getTextSample(aText)
  set aLen to length of aText
  
if aLen < 1024 then
    set bLen to aLen
  else
    set bLen to 1024
  end if
  
return (text 1 thru bLen of aText)
end getTextSample

★Click Here to Open This Script 

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

UniversalDetectorで文字コード判定

Posted on 2月 8, 2018 by Takaaki Naganoya

UniversalDetector.frameworkを呼び出して指定のテキストファイルの文字コードを判定するAppleScriptです。

日本語のテキストで実験してみたところ、UTF-16系以外は正常に判定できています。日本語以外の言語を対象にした場合には使い手がありそうですが、日本語を対象にした場合には、「文字エンコーディングを自動判別してファイル読み込み v1.2.1」のほうが便利です。

–> UniversalDetector.framework

AppleScript名:UniversalDetectorで文字コード判定
— Created 2015-10-03 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "UniversalDetector" –https://github.com/JanX2/UniversalDetector

set aPath to (POSIX path of (choose file))
set aStr to current application’s NSString’s stringWithString:aPath
set aDetector to current application’s UniversalDetector’s new()
aDetector’s analyzeContentsOfFile:aStr
set aStr to current application’s NSString’s localizedNameOfStringEncoding:(aDetector’s encoding())

–>  (NSString) "日本語(EUC)"
–>  (NSString) "日本語(ISO 2022-JP)"
–>  (NSString) "日本語(Shift JIS)"
–>  (NSString) "Unicode(UTF-8)"
–>  (NSString) "キリル文字(Windows)" –NG。本当はUTF-16 no BOM
–>  (NSString) "中国語(GB 18030)"–NG。本当はUTF-16BE
–>  (NSString) "Unicode(UTF-16)"

set bStr to aDetector’s MIMECharset()

–>  (NSString) "EUC-JP"
–>  (NSString) "ISO-2022-JP"
–>  (NSString) "Shift_JIS"
–>  (NSString) "UTF-8"
–>  (NSString) "windows-1251"–NG
–>  (NSString) "gb18030"–NG
–>  (NSString) "UTF-16"

set aNum to (aDetector’s confidence()) * 100
–>  100.0–"EUC-JP"
–>  100.0–"ISO-2022-JP"
–>  100.0–"Shift_JIS"
–>  100.0–"UTF-8"
–>  5.271286144853–UTF-16 no BOM
–>  100.0–NGだが100%といっている
–>  100.0– "UTF-16"

return {aStr as string, bStr as string, aNum}

★Click Here to Open This Script 

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

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • macOS 15, Sequoia
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • Numbersで選択範囲のセルの前後の空白を削除
  • メキシカンハットの描画
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • AppleScriptによる並列処理
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • macOS 15でも変化したText to Speech環境
  • AppleScript入門③AppleScriptを使った「自動化」とは?
  • デフォルトインストールされたフォント名を取得するAppleScript
  • macOS 15 リモートApple Eventsにバグ?
  • 【続報】macOS 15.5で特定ファイル名パターンのfileをaliasにcastすると100%クラッシュするバグ
  • AppleScript入門① AppleScriptってなんだろう?
  • Script Debuggerの開発と販売が2025年に終了
  • macOS 14で変更になったOSバージョン取得APIの返り値
  • NSObjectのクラス名を取得 v2.1
  • 有害ではなくなっていたSpaces
  • macOS 15:スクリプトエディタのAppleScript用語辞書を確認できない
  • Xcode上のAppleScriptObjCのプログラムから、Xcodeのログ欄へのメッセージ出力を実行

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1391) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (194) 14.0savvy (147) 15.0savvy (135) CotEditor (66) Finder (51) iTunes (19) 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 (55) 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
  • 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
  • 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年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