Text CSV

CSVクオテーション方式判定


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# CSV クオテーションの有無の判定
#
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application
property refNSNotFound : a reference to 9.22337203685477E+18 + 5807

###Wクリックで起動した場合
on run
  ###ダイアログ
  tell current application
    set strName to name as text
  end tell
  ####スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder" to activate
  else
    tell current application to activate
  end if
  ############ デフォルトロケーション
  set appFileManager to refMe's NSFileManager's defaultManager()
  set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
  set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
  set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias
  #
  set listUTI to {"public.comma-separated-values-text"}
  set strMes to ("ファイルを選んでください") as text
  set strPrompt to ("ファイルを選んでください") as text
  try
    ### ファイル選択時
    set listAliasFilePath to (choose file strMes with prompt strPrompt default location aliasDesktopDirPath of type listUTI with invisibles, multiple selections allowed and showing package contents) as list
  on error
log "エラーしました"
return "エラーしました"
  end try
  if listAliasFilePath is {} then
return "選んでください"
  end if
open listAliasFilePath
end run


on open listAliasFilePath
  
  repeat with itemAliasFilePath in listAliasFilePath
    ##パス
    set aliasFilePath to itemAliasFilePath as alias
    set strFilePath to (POSIX path of aliasFilePath) as text
    set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
    set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
    set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
    ############################
    #ファイルのテキストを読み込み
    set listResponse to (refMe's NSString's alloc()'s initWithContentsOfURL:(ocidFilePathURL) usedEncoding:(refMe's NSUTF8StringEncoding) |error|:(reference))
    set ocidReadString to (item 1 of listResponse)
    if ocidReadString = (missing value) then
      set strFileName to ocidFilePathURL's lastPathComponent() as text
log "文字コードを判定出来ませんでした : " & strFileName
      ############################
      #文字コード指定で読み込む
      #ユーザー選択用のレコード
      set recordEnc to {|NSISO2022JPStringEncoding|:(refMe's NSISO2022JPStringEncoding), |NSJapaneseEUCStringEncoding|:(refMe's NSJapaneseEUCStringEncoding), |NSShiftJISStringEncoding|:(refMe's NSShiftJISStringEncoding), |NSUTF8StringEncoding|:(refMe's NSUTF8StringEncoding), |NSUTF16LittleEndianStringEncoding|:(refMe's NSUTF16LittleEndianStringEncoding), |NSUTF16StringEncoding|:(refMe's NSUTF16StringEncoding), |NSUnicodeStringEncoding|:(refMe's NSUnicodeStringEncoding), |NSUTF32LittleEndianStringEncoding|:(refMe's NSUTF32LittleEndianStringEncoding), |NSUTF32StringEncoding|:(refMe's NSUTF32StringEncoding), |NSWindowsCP1250StringEncoding|:(refMe's NSWindowsCP1250StringEncoding), |NSWindowsCP1251StringEncoding|:(refMe's NSWindowsCP1251StringEncoding), |NSWindowsCP1252StringEncoding|:(refMe's NSWindowsCP1252StringEncoding), |NSWindowsCP1253StringEncoding|:(refMe's NSWindowsCP1253StringEncoding), |NSWindowsCP1254StringEncoding|:(refMe's NSWindowsCP1254StringEncoding), |NSASCIIStringEncoding|:(refMe's NSASCIIStringEncoding), |NSISOLatin1StringEncoding|:(refMe's NSISOLatin1StringEncoding), |NSISOLatin2StringEncoding|:(refMe's NSISOLatin2StringEncoding), |NSMacOSRomanStringEncoding|:(refMe's NSMacOSRomanStringEncoding), |NSNonLossyASCIIStringEncoding|:(refMe's NSNonLossyASCIIStringEncoding)} as record
      #Dictに入れて
      set ocidEncDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidEncDict's setDictionary:(recordEnc))
      #ダイアログ用にキー名称のみ取り出す
      set ocidAllKey to ocidEncDict's allKeys()
      #A-z順に並び替え
      set ocidSortedAllKey to (ocidAllKey's sortedArrayUsingSelector:("localizedStandardCompare:"))
      #リストにしてダイアログに渡す
      set listSortedAllKey to ocidSortedAllKey as list
      ###ダイアログを前面に出す
      set strName to (name of current application) as text
      if strName is "osascript" then
        tell application "Finder" to activate
      else
        tell current application to activate
      end if
      #
      set strTitle to ("選んでください") as text
      set strPrompt to ("保存エンコードを選んでください\nUTF16-32は通常LEを選んでください") as text
      try
        set listResponse to (choose from list listSortedAllKey with title strTitle with prompt strPrompt default items (item 5 of listSortedAllKey) OK button name "OK" cancel button name "キャンセル" without multiple selections allowed and empty selection allowed) as list
      on error
log "エラーしました"
return "エラーしました"
      end try
      if (item 1 of listResponse) is false then
return "キャンセルしましたA"
      else if (item 1 of listResponse) is {} then
return "キャンセルしましたB"
      end if
      #戻り値
      set strResponse to (item 1 of listResponse) as text
      #戻り値をキーにして値=この場合はテキストエンコードを取り出しておく
      set ocidSetEnc to (ocidEncDict's objectForKey:(strResponse))
log className() of ocidSetEnc as text
      #指定文字コード読み込み
      set listResponse to (refMe's NSString's alloc()'s initWithContentsOfURL:(ocidFilePathURL) encoding:(ocidSetEnc) |error|:(reference))
      set ocidReadString to (item 1 of listResponse)
      if ocidReadString = (missing value) then
return "指定文字コードで読み込み出来ませんでした : " & strFileName
      end if
    end if
    ############################
    #改行コード判定
    set ocidCrRange to (ocidReadString's rangeOfString:("\r"))'s location()
    set ocidLfRange to (ocidReadString's rangeOfString:("\n"))'s location()
    if ocidCrRange = refNSNotFound then
log "Mac改行は無い"
      if ocidLfRange = refNSNotFound then
log "Mac改行もUNIX改行は無い=改行の無い1行か空のテキスト"
        set ocidLength to ocidReadString's |length|
        if ocidLength = (refMe's NSNumber's numberWithInteger:0) then
log "空のテキスト"
          set ocidNewLineChar to ocidSetNewLineChar
        else
log "改行無しの1行テキスト"
          set ocidNewLineChar to ocidSetNewLineChar
        end if
      else
log "Mac改行無+UNIX改行あり=UNIX改行"
        set ocidNewLineChar to (refMe's NSString's stringWithString:("\n"))
      end if
    else
      if ocidLfRange = refNSNotFound then
log "MacがあるUNIX改行は無い=Mac改行"
        set ocidNewLineChar to (refMe's NSString's stringWithString:("\r"))
      else
log "Mac改行ある+UNIX改行あり=Windows改行"
        set ocidNewLineChar to (refMe's NSString's stringWithString:("\r\n"))
      end if
    end if
    #改行毎でリストにする
    set ocidLineArray to (ocidReadString's componentsSeparatedByString:(ocidNewLineChar))
    ############################
    # 区切り方式判定
    #最初の1行目を取得
    set ocidItemRowText to (ocidLineArray's firstObject())
    #1文字目を取得するためのレンジ
    set ocidRange to refMe's NSMakeRange(0, 1)
    #1文字目を取得
    set strFirstChar to (ocidItemRowText's substringWithRange:(ocidRange)) as text
    # カンマ区切り方式の判定
    if strFirstChar is "\"" then
log "クオテーション形式のCSV"
      set ocidSchar to (refMe's NSString's stringWithString:("\",\""))
    else
log "通常のCSV"
      set ocidSchar to (refMe's NSString's stringWithString:(","))
    end if
    ############################
    # 本処理
    ############################
    #行順に処理
    repeat with itemLineArray in ocidLineArray
      # 行のテキストをカンマ区切り方式毎にリストに
      set ocidRowArray to (itemLineArray's componentsSeparatedByString:(ocidSchar))
      # 区切り毎順の処理
      repeat with itemRowArray in ocidRowArray
        ##これが区切り毎のテキスト
log itemRowArray as text
        
      end repeat
    end repeat
    
    
    
  end repeat
  
end open




|

CSV2TSV 修正


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# CSV2TSV
# クオテーション有りのCSVの処理を修正した
# 文字コードが判定出来ない場合停止するようにした
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKIt"
use framework "UniformTypeIdentifiers"
use scripting additions

property refMe : a reference to current application

###Wクリックで起動した場合
on run
  ###ダイアログ
  tell current application
    set strName to name as text
  end tell
  ####スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder" to activate
  else
    tell current application to activate
  end if
  ############ デフォルトロケーション
  set appFileManager to refMe's NSFileManager's defaultManager()
  set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
  set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
  set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias
  #
  set listUTI to {"public.comma-separated-values-text"}
  set strMes to ("ファイルを選んでください") as text
  set strPrompt to ("ファイルを選んでください") as text
  try
    ### ファイル選択時
    set listAliasFilePath to (choose file strMes with prompt strPrompt default location aliasDesktopDirPath of type listUTI with invisibles, multiple selections allowed and showing package contents) as list
  on error
log "エラーしました"
return "エラーしました"
  end try
  if listAliasFilePath is {} then
return "選んでください"
  end if
open listAliasFilePath
end run


on open listAliasFilePath
  
  repeat with itemAliasFilePath in listAliasFilePath
    ##パス
    set aliasFilePath to itemAliasFilePath as alias
    set strFilePath to (POSIX path of aliasFilePath) as text
    set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
    set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
    set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
    #保存するタブ区切りテキストのパス
    set ocidBaseFilePathURL to ocidFilePathURL's URLByDeletingPathExtension()
    set ocidSaveFilePathURL to (ocidBaseFilePathURL's URLByAppendingPathExtension:("tsv"))
    
    #ファイルのテキストを読み込み
    # set listResponse to (refMe's NSString's alloc()'s initWithContentsOfURL:(ocidFilePathURL) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference))
    # set ocidReadString to (item 1 of listResponse)
    set listResponse to (refMe's NSString's alloc()'s initWithContentsOfURL:(ocidFilePathURL) usedEncoding:(refMe's NSUTF8StringEncoding) |error|:(reference))
    set ocidReadString to (item 1 of listResponse)
    if ocidReadString = (missing value) then
      set strFileName to ocidFilePathURL's lastPathComponent() as text
return "文字コードを判定出来ませんでした : " & strFileName
    end if
    #出力用のテキスト
    set ocidOutPutString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
    #ユニックス改行の数を調べて
    set ocidCharSet to (refMe's NSCharacterSet's characterSetWithCharactersInString:("\n"))
    set ocidLineArrayN to (ocidReadString's componentsSeparatedByCharactersInSet:(ocidCharSet))
    set numCntLineNoN to (count of ocidLineArrayN) as integer
    #改行キャラクタ\nと\rの数をそれぞれ数えて
    set ocidCharSet to (refMe's NSCharacterSet's newlineCharacterSet)
    set ocidLineArrayNL to (ocidReadString's componentsSeparatedByCharactersInSet:(ocidCharSet))
    set numCntLineNoNL to (count of ocidLineArrayNL) as integer
    #改行方式でテキストを行毎処理としてリストにする
    #UNIX改行の数と改行キャラクタの数が同じならUNIX改行
    
    if numCntLineNoN = numCntLineNoNL then
log "UNIX改行です"
      set strNewlineCharacter to ("\n") as text
      set ocidLineArray to ocidLineArrayN
      #改行がない1行ならMacの可能性が高い
    else if numCntLineNoN = 1 then
      #\rが複数あるならまぁMac改行で間違い無いでしょ
      if numCntLineNoNL > 1 then
log "Mac改行です"
        set strNewlineCharacter to ("\r") as text
        set ocidCharSet to (refMe's NSCharacterSet's characterSetWithCharactersInString:(strNewlineCharacter))
        set ocidLineArray to (ocidReadString's componentsSeparatedByCharactersInSet:(ocidCharSet))
      else
return "処理中止"
      end if
      #UNIX改行の数より改行キャラクタの数が多いならWIN改行
    else if numCntLineNoNL > numCntLineNoN then
log "Windows改行です"
      #WINDOWS改行はUNIX改行に置換してからArray処理する
      set strNewlineCharacter to ("\r\n") as text
      set ocidWindowsString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
(ocidWindowsString's setString:(ocidReadString))
      set ocidReadString to (ocidWindowsString's stringByReplacingOccurrencesOfString:(strNewlineCharacter) withString:("\n"))
      set ocidCharSet to (refMe's NSCharacterSet's characterSetWithCharactersInString:(strNewlineCharacter))
      set ocidLineArray to (ocidReadString's componentsSeparatedByCharactersInSet:(ocidCharSet))
    else
return "処理中止"
    end if
    #クオテーション処理の有無を調べる
    set ocidFirstLine to ocidLineArray's firstObject()
    set ocidRange to refMe's NSMakeRange(0, 1)
    set strFirstChar to (ocidFirstLine's substringWithRange:(ocidRange)) as text
    if strFirstChar is "\"" then
log "クオテーション形式のCSV"
      set strSchar to ("\",\"") as text
    else
log "通常のCSV"
      set strSchar to (",") as text
    end if
    #行毎の処理
    repeat with itemLineString in ocidLineArray
      if (itemLineString as text) is "" then
        ##空行=最後の行に改行がある場合は終了
        exit repeat
      end if
      #行のテキストを可変テキストに入れて
      set ocidLineString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
(ocidLineString's setString:(itemLineString))
      #区切り文字でタブに置換
      set ocidTabLineString to (ocidLineString's stringByReplacingOccurrencesOfString:(strSchar) withString:("\t"))
      set strFirstChar to (ocidTabLineString's substringToIndex:(1)) as text
      set numCharLengh to ocidTabLineString's |length| as integer
      set strLastChar to (ocidTabLineString's substringFromIndex:(numCharLengh - 1)) as text
      if strFirstChar is "\"" then
        set ocidRange to refMe's NSMakeRange(0, 1)
(ocidTabLineString's deleteCharactersInRange:(ocidRange))
      end if
      if strLastChar is "\"" then
        set numCharLengh to ocidTabLineString's |length| as integer
        set ocidRange to refMe's NSMakeRange((numCharLengh - 1), 1)
(ocidTabLineString's deleteCharactersInRange:(ocidRange))
      end if
      #出力用のテキストにセット
(ocidOutPutString's appendString:(ocidTabLineString))
      #改行を付与
(ocidOutPutString's appendString:(strNewlineCharacter))
    end repeat
    #保存
    set listDone to (ocidOutPutString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference))
    
  end repeat
  
end open

|

[CSV2TSV]カンマ区切りテキストをタブテキストに変換する 修正


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# CSV2TSV
# クオテーション有りのCSVの処理を修正した
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKIt"
use framework "UniformTypeIdentifiers"
use scripting additions

property refMe : a reference to current application

###Wクリックで起動した場合
on run
  ###ダイアログ
  tell current application
    set strName to name as text
  end tell
  ####スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder" to activate
  else
    tell current application to activate
  end if
  ############ デフォルトロケーション
  set appFileManager to refMe's NSFileManager's defaultManager()
  set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
  set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
  set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias
  #
  set listUTI to {"public.comma-separated-values-text"}
  set strMes to ("ファイルを選んでください") as text
  set strPrompt to ("ファイルを選んでください") as text
  try
    ### ファイル選択時
    set listAliasFilePath to (choose file strMes with prompt strPrompt default location aliasDesktopDirPath of type listUTI with invisibles, multiple selections allowed and showing package contents) as list
  on error
log "エラーしました"
return "エラーしました"
  end try
  if listAliasFilePath is {} then
return "選んでください"
  end if
open listAliasFilePath
end run


on open listAliasFilePath
  
  repeat with itemAliasFilePath in listAliasFilePath
    ##パス
    set aliasFilePath to itemAliasFilePath as alias
    set strFilePath to (POSIX path of aliasFilePath) as text
    set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
    set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
    set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
    #保存するタブ区切りテキストのパス
    set ocidBaseFilePathURL to ocidFilePathURL's URLByDeletingPathExtension()
    set ocidSaveFilePathURL to (ocidBaseFilePathURL's URLByAppendingPathExtension:("tsv"))
    #ファイルのテキストを読み込み
    set listResponse to (refMe's NSString's alloc()'s initWithContentsOfURL:(ocidFilePathURL) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference))
    set ocidReadString to (item 1 of listResponse)
    #出力用のテキスト
    set ocidOutPutString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
    #ユニックス改行の数を調べて
    set ocidCharSet to (refMe's NSCharacterSet's characterSetWithCharactersInString:("\n"))
    set ocidLineArrayN to (ocidReadString's componentsSeparatedByCharactersInSet:(ocidCharSet))
    set numCntLineNoN to (count of ocidLineArrayN) as integer
    #改行キャラクタ\nと\rの数をそれぞれ数えて
    set ocidCharSet to (refMe's NSCharacterSet's newlineCharacterSet)
    set ocidLineArrayNL to (ocidReadString's componentsSeparatedByCharactersInSet:(ocidCharSet))
    set numCntLineNoNL to (count of ocidLineArrayNL) as integer
    #改行方式でテキストを行毎処理としてリストにする
    #UNIX改行の数と改行キャラクタの数が同じならUNIX改行
    
    if numCntLineNoN = numCntLineNoNL then
log "UNIX改行です"
      set strNewlineCharacter to ("\n") as text
      set ocidLineArray to ocidLineArrayN
      #改行がない1行ならMacの可能性が高い
    else if numCntLineNoN = 1 then
      #\rが複数あるならまぁMac改行で間違い無いでしょ
      if numCntLineNoNL > 1 then
log "Mac改行です"
        set strNewlineCharacter to ("\r") as text
        set ocidCharSet to (refMe's NSCharacterSet's characterSetWithCharactersInString:(strNewlineCharacter))
        set ocidLineArray to (ocidReadString's componentsSeparatedByCharactersInSet:(ocidCharSet))
      else
return "処理中止"
      end if
      #UNIX改行の数より改行キャラクタの数が多いならWIN改行
    else if numCntLineNoNL > numCntLineNoN then
log "Windows改行です"
      #WINDOWS改行はUNIX改行に置換してからArray処理する
      set strNewlineCharacter to ("\r\n") as text
      set ocidWindowsString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
(ocidWindowsString's setString:(ocidReadString))
      set ocidReadString to (ocidWindowsString's stringByReplacingOccurrencesOfString:(strNewlineCharacter) withString:("\n"))
      set ocidCharSet to (refMe's NSCharacterSet's characterSetWithCharactersInString:(strNewlineCharacter))
      set ocidLineArray to (ocidReadString's componentsSeparatedByCharactersInSet:(ocidCharSet))
    else
return "処理中止"
    end if
    #クオテーション処理の有無を調べる
    set ocidFirstLine to ocidLineArray's firstObject()
    set ocidRange to refMe's NSMakeRange(0, 1)
    set strFirstChar to (ocidFirstLine's substringWithRange:(ocidRange)) as text
    if strFirstChar is "\"" then
log "クオテーション形式のCSV"
      set strSchar to ("\",\"") as text
    else
log "通常のCSV"
      set strSchar to (",") as text
    end if
    #行毎の処理
    repeat with itemLineString in ocidLineArray
      if (itemLineString as text) is "" then
        ##空行=最後の行に改行がある場合は終了
        exit repeat
      end if
      #行のテキストを可変テキストに入れて
      set ocidLineString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
(ocidLineString's setString:(itemLineString))
      #区切り文字でタブに置換
      set ocidTabLineString to (ocidLineString's stringByReplacingOccurrencesOfString:(strSchar) withString:("\t"))
      set strFirstChar to (ocidTabLineString's substringToIndex:(1)) as text
      set numCharLengh to ocidTabLineString's |length| as integer
      set strLastChar to (ocidTabLineString's substringFromIndex:(numCharLengh - 1)) as text
      if strFirstChar is "\"" then
        set ocidRange to refMe's NSMakeRange(0, 1)
(ocidTabLineString's deleteCharactersInRange:(ocidRange))
      end if
      if strLastChar is "\"" then
        set numCharLengh to ocidTabLineString's |length| as integer
        set ocidRange to refMe's NSMakeRange((numCharLengh - 1), 1)
(ocidTabLineString's deleteCharactersInRange:(ocidRange))
      end if
      #出力用のテキストにセット
(ocidOutPutString's appendString:(ocidTabLineString))
      #改行を付与
(ocidOutPutString's appendString:(strNewlineCharacter))
    end repeat
    #保存
    set listDone to (ocidOutPutString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference))
    
  end repeat
  
end open

|

[CSV2TSV]カンマ区切りテキストをタブテキストに変換する

修正版があります
[CSV2TSV]カンマ区切りテキストをタブテキストに変換する 修正
https://quicktimer.cocolog-nifty.com/icefloe/2024/02/post-4e819f.html

【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKIt"
use framework "UniformTypeIdentifiers"
use scripting additions

property refMe : a reference to current application

###Wクリックで起動した場合
on run
  ###ダイアログ
  tell current application
    set strName to name as text
  end tell
  ####スクリプトメニューから実行したら
  if strName is "osascript" then
    tell application "Finder" to activate
  else
    tell current application to activate
  end if
  ############ デフォルトロケーション
  set appFileManager to refMe's NSFileManager's defaultManager()
  set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
  set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
  set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias
  #
  set listUTI to {"public.comma-separated-values-text"}
  set strMes to ("ファイルを選んでください") as text
  set strPrompt to ("ファイルを選んでください") as text
  try
    ### ファイル選択時
    set listAliasFilePath to (choose file strMes with prompt strPrompt default location aliasDesktopDirPath of type listUTI with invisibles, multiple selections allowed and showing package contents) as list
  on error
log "エラーしました"
return "エラーしました"
  end try
  if listAliasFilePath is {} then
return "選んでください"
  end if
open listAliasFilePath
end run


on open listAliasFilePath
  
  repeat with itemAliasFilePath in listAliasFilePath
    ##パス
    set aliasFilePath to itemAliasFilePath as alias
    set strFilePath to (POSIX path of aliasFilePath) as text
    set ocidFilePathStr to (refMe's NSString's stringWithString:(strFilePath))
    set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
    set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)
    #保存するタブ区切りテキストのパス
    set ocidBaseFilePathURL to ocidFilePathURL's URLByDeletingPathExtension()
    set ocidSaveFilePathURL to (ocidBaseFilePathURL's URLByAppendingPathExtension:("tsv"))
    #ファイルのテキストを読み込み
    set listResponse to (refMe's NSString's alloc()'s initWithContentsOfURL:(ocidFilePathURL) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference))
    set ocidReadString to (item 1 of listResponse)
    #出力用のテキスト
    set ocidOutPutString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
    #改行を調べて
    set ocidCharSet to (refMe's NSCharacterSet's characterSetWithCharactersInString:("\n"))
    set ocidLineArrayN to (ocidReadString's componentsSeparatedByCharactersInSet:(ocidCharSet))
    set numCntLineNoN to (count of ocidLineArrayN) as integer
    set ocidCharSet to (refMe's NSCharacterSet's newlineCharacterSet)
    set ocidLineArrayNL to (ocidReadString's componentsSeparatedByCharactersInSet:(ocidCharSet))
    set numCntLineNoNL to (count of ocidLineArrayNL) as integer
    #改行方式でテキストを行毎処理としてリストにする
    if ocidLineArrayN = ocidLineArrayNL then
log "UNIX改行です"
      set strNewlineCharacter to ("\n") as text
      set ocidLineArray to ocidLineArrayN
    else if numCntLineNoN = 1 then
      if numCntLineNoNL > 1 then
log "Mac改行です"
        set strNewlineCharacter to ("\r") as text
        set ocidCharSet to (refMe's NSCharacterSet's characterSetWithCharactersInString:(strNewlineCharacter))
        set ocidLineArray to (ocidReadString's componentsSeparatedByCharactersInSet:(ocidCharSet))
      else
return "処理中止"
      end if
    else if numCntLineNoNL > numCntLineNoN then
log "Windows改行です"
      #WINDOWS改行はUNIX改行に置換してからArray処理する
      set strNewlineCharacter to ("\r\n") as text
      set ocidWindowsString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
(ocidWindowsString's setString:(ocidReadString))
      set ocidReadString to (ocidWindowsString's stringByReplacingOccurrencesOfString:(strNewlineCharacter) withString:("\n"))
      set ocidCharSet to (refMe's NSCharacterSet's characterSetWithCharactersInString:(strNewlineCharacter))
      set ocidLineArray to (ocidReadString's componentsSeparatedByCharactersInSet:(ocidCharSet))
    else
return "処理中止"
    end if
    #クオテーション処理の有無を調べる
    set ocidFirstLine to ocidLineArray's firstObject()
    set ocidRange to refMe's NSMakeRange(0, 1)
    set strFirstChar to (ocidFirstLine's substringWithRange:(ocidRange)) as text
    if strFirstChar is "\"" then
log "クオテーション形式のCSV"
      set strSchar to ("\",\"") as text
    else
log "通常のCSV"
      set strSchar to (",") as text
    end if
    #行毎の処理
    repeat with itemLineString in ocidLineArray
      if (itemLineString as text) is "" then
        ##空行=最後の行に改行がある場合は終了
        exit repeat
      end if
      #行のテキストを可変テキストに入れて
      set ocidLineString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
(ocidLineString's setString:(itemLineString))
      #区切り文字でタブに置換
      set ocidTabLineString to (ocidLineString's stringByReplacingOccurrencesOfString:(strSchar) withString:("\t"))
      #出力用のテキストにセット
(ocidOutPutString's appendString:(ocidTabLineString))
      #改行を付与
(ocidOutPutString's appendString:(strNewlineCharacter))
    end repeat
    #保存
    set listDone to (ocidOutPutString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference))
    
  end repeat
  
end open

|

郵便番号検索 v2

都道府県+市区町村名に対応

ダウンロード - 郵便番号検索v2.zip


【スクリプトエディタで開く】|

#!/bin/bash
# V2 都道府県市区町村を追加
#com.cocolog-nifty.quicktimer.icefloe
##################################################
###設定項目 CSVのファイル名
STR_CSV_FILE_NAME="utf_all.csv"
### path to me
SCRIPT_PATH="${BASH_SOURCE[0]}"
/bin/echo "このスクリプトのパス $SCRIPT_PATH"
STR_CONTAINER_DIR_PATH=$(/usr/bin/dirname "$SCRIPT_PATH")
/bin/echo "コンテナディレクトリ $STR_CONTAINER_DIR_PATH"
STR_DATA_DIR_PATH="$STR_CONTAINER_DIR_PATH/data"
/bin/mkdir -p "$STR_DATA_DIR_PATH"
/bin/echo "データ格納ディレクトリ $STR_DATA_DIR_PATH"
STR_CSV_FILE_PATH="$STR_DATA_DIR_PATH/$STR_CSV_FILE_NAME"
/bin/echo "CSVのファイルパス $STR_CSV_FILE_PATH"
STR_IMPORT_FILE_PATH="$STR_DATA_DIR_PATH/$STR_CSV_FILE_NAME.import.csv"
/bin/echo "SQLインポート用CSVの書き出しパス $STR_IMPORT_FILE_PATH"
STR_DB_FILE_PATH="$STR_DATA_DIR_PATH/postno.db"
/bin/echo "SQLDBのパス $STR_DB_FILE_PATH"
##################################################
###古いデータは削除する
/usr/bin/touch "$STR_IMPORT_FILE_PATH"
/usr/bin/touch "$STR_DB_FILE_PATH"
/usr/bin/touch "$STR_CSV_FILE_PATH"
/bin/rm  "$STR_IMPORT_FILE_PATH"
/bin/rm  "$STR_DB_FILE_PATH"
/bin/rm  "$STR_CSV_FILE_PATH"
##################################################
STR_URL="https://www.post.japanpost.jp/zipcode/dl/utf/zip/utf_all.zip"
###ダウンロード起動時に削除する項目
USER_TEMP_DIR=$(/usr/bin/mktemp -d)
/bin/echo "起動時に削除されるディレクトリ $USER_TEMP_DIR"
if ! /usr/bin/curl -L -o "$USER_TEMP_DIR/utf_all.zip" "$STR_URL" --connect-timeout 20; then
  /bin/echo "ファイルのダウンロードに失敗しました HTTP1.1で再トライします"
  if ! /usr/bin/curl -L -o "$USER_TEMP_DIR/utf_all.zip" "$STR_URL" --http1.1 --connect-timeout 20; then
    /bin/echo "ファイルのダウンロードに失敗しました"
    exit 1
  fi
fi
/bin/echo "ダウンロードしたZIPファイル $USER_TEMP_DIR/utf_all.zip"
##################################################
###解凍
/usr/bin/cd "$STR_DATA_DIR_PATH"
/usr/bin/bsdtar -xzvf "$USER_TEMP_DIR/utf_all.zip" -C "$STR_DATA_DIR_PATH"
/bin/echo "ダウンロードデータ解凍OK"
##################################################
###クオテーション除去
STR_TMP_FILE_PATH="$USER_TEMP_DIR/$STR_CSV_FILE_NAME.tmp.csv"
/usr/bin/sed 's/"//g' "$STR_CSV_FILE_PATH" > "$STR_TMP_FILE_PATH"
###改行変更
/usr/bin/sed 's/\r$//' "$STR_TMP_FILE_PATH" > "$STR_IMPORT_FILE_PATH"
/bin/echo "データ整形終了"
##################################################
###1行目挿入 この処理は不要だった
## STR_HEADER_TEXT="code,old_no,p_no,prefecture_kana,city_kana,town_kana,prefecture,city,town,more,aza,cho,contain,update,change"
## /usr/bin/touch "$STR_IMPORT_FILE_PATH"
## /bin/echo "$STR_HEADER_TEXT" > "$STR_IMPORT_FILE_PATH"
## /bin/cat "$STR_TMPB_FILE_PATH" >> "$STR_IMPORT_FILE_PATH"
##################################################
/bin/echo "データインポート開始"
###インポート DB作成
/usr/bin/sqlite3 "$STR_DB_FILE_PATH" <<EOF
CREATE TABLE postalcode (code TEXT,old_no TEXT,p_no TEXT,prefecture_kana TEXT,city_kana TEXT,town_kana TEXT,prefecture TEXT,city TEXT,town TEXT,more INTEGER,azamore INTEGER,chomore INTEGER,containmore INTEGER,updatemore INTEGER,changemore INTEGER);
.mode csv
.import "$STR_IMPORT_FILE_PATH" postalcode
EOF
/bin/echo "データインポート終了"
sleep 2
/bin/echo "都道府県+地区町村作成開始"
/usr/bin/sqlite3 "$STR_DB_FILE_PATH" <<EOF
ALTER TABLE postalcode ADD COLUMN pref_and_city TEXT;
EOF
/bin/echo "都道府県+地区町村作成開始 OK"

/bin/echo "都道府県+地区町村 データ結合開始"
/usr/bin/sqlite3 "$STR_DB_FILE_PATH" <<EOF
UPDATE postalcode SET pref_and_city = prefecture || city;
EOF
/bin/echo "都道府県+地区町村 データ結合開始 ok"


/bin/echo "処理終了しました"
exit 0



【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# V2 都道府県市区町村を追加
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions

property refMe : a reference to current application
property refNSNotFound : a reference to 9.22337203685477E+18 + 5807



#############################
### クリップボードの中身取り出し
###初期化
set ocidPasteboard to refMe's NSPasteboard's generalPasteboard()
set ocidPastBoardTypeArray to ocidPasteboard's types
###テキストがあれば
set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
if boolContain = true then
  ###値を格納する
  tell application "Finder"
    set strReadString to (the clipboard as text) as text
  end tell
  ###Finderでエラーしたら
else
  set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
  if boolContain = true then
    set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
    set strReadString to ocidReadString as text
  else
    log "テキストなし"
    set strReadString to "" as text
  end if
end if



#############################
###DBファイルへのパス
tell application "Finder"
  set aliasPathToMe to (path to me) as alias
  set aliasContainerDirPath to (container of aliasPathToMe) as alias
end tell
set strContainerDirPath to (POSIX path of aliasContainerDirPath) as text
set ocidContainerDirPathStr to refMe's NSString's stringWithString:(strContainerDirPath)
set ocidContainerDirPath to ocidContainerDirPathStr's stringByStandardizingPath()
set ocidContainerDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidContainerDirPath) isDirectory:true)
set ocidDBFilePathURL to ocidContainerDirPathURL's URLByAppendingPathComponent:("data/postno.db")
set strDbFilePathURL to (ocidDBFilePathURL's |path|()) as text

set strMes to ("住所で検索 一部分でも可\r神奈川とかで指定すると検索結果が多くなります") as text
set strQueryText to strReadString as text

##############################
###ダイアログ
set strName to (name of current application) as text
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
set aliasIconPath to POSIX file "/System/Applications/Calculator.app/Contents/Resources/AppIcon.icns" as alias
try
  set recordResult to (display dialog strMes with title "郵便番号検索" default answer strQueryText buttons {"OK", "キャンセル"} default button "OK" with icon aliasIconPath giving up after 20 without hidden answer) as record
  if "OK" is equal to (button returned of recordResult) then
    set strReturnedText to (text returned of recordResult) as text
  else if (gave up of recordResult) is true then
return "時間切れです"
  else
return "キャンセル"
  end if
on error
  log "エラーしました"
return
end try
##############################
###戻り値整形
set ocidResponseText to (refMe's NSString's stringWithString:(strReturnedText))
###タブと改行を除去しておく
set ocidTextM to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
ocidTextM's appendString:(ocidResponseText)
##改行除去
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\n") withString:("")
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\r") withString:("")
##タブ除去
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\t") withString:("")
##############################
###ひらがなのみの場合はカタカナに
set listRegex to refMe's NSRegularExpression's regularExpressionWithPattern:("^[ぁ-んー]+$") options:(0) |error|:(reference)
set ocidRegex to (item 1 of listRegex)
set ocidTextRange to refMe's NSMakeRange(0, (ocidTextM's |length|()))
log ocidTextRange
set numMach to ocidRegex's numberOfMatchesInString:(ocidTextM) options:0 range:(ocidTextRange)
if (numMach as integer) = 1 then
  set ocidTransform to (refMe's NSStringTransformHiraganaToKatakana)
  set ocidTextM to (ocidTextM's stringByApplyingTransform:(ocidTransform) |reverse|:false)
end if
###数字がなければ全角に
set ocidTransform to (refMe's NSStringTransformFullwidthToHalfwidth)
set ocidTextM to (ocidTextM's stringByApplyingTransform:(ocidTransform) |reverse|:true)
##############################
##カタカナと漢字混在で検索方法が異なる
set listRegex to refMe's NSRegularExpression's regularExpressionWithPattern:("^[ァ-ヶー]+$") options:(0) |error|:(reference)
set ocidRegex to (item 1 of listRegex)
set ocidTextRange to refMe's NSMakeRange(0, (ocidTextM's |length|()))
set numMach to ocidRegex's numberOfMatchesInString:(ocidTextM) options:0 range:(ocidTextRange)
set strSearchText to ocidTextM as text
if (numMach as integer) = 1 then
  set strCommandText to ("/usr/bin/sqlite3 \"" & strDbFilePathURL & "\" -tabs \"SELECT COUNT(*) FROM postalcode WHERE prefecture_kana LIKE '%" & strSearchText & "%' OR city_kana LIKE '%" & strSearchText & "%' OR town_kana LIKE '%" & strSearchText & "%';\"") as text
  log strCommandText
else
  set strCommandText to ("/usr/bin/sqlite3 \"" & strDbFilePathURL & "\" -tabs \"SELECT COUNT(*) FROM postalcode WHERE prefecture LIKE '%" & strSearchText & "%' OR city LIKE '%" & strSearchText & "%' OR town LIKE '%" & strSearchText & "%' OR pref_and_city LIKE '%" & strSearchText & "%';\"") as text
  log strCommandText
end if
###検索結果の件数
set numQueryCnt to (do shell script strCommandText) as integer
##############################
###件数が100超える場合は中止を促す
if numQueryCnt > 100 then
  log "検索結果100件超です"
  ###ダイアログを前面に出す
  set strName to (name of current application) as text
  if strName is "osascript" then
    tell application "Finder" to activate
  else
    tell current application to activate
  end if
  ##1件の処理時間
  set numMin to (0.01 * numQueryCnt) as integer
  set strAlertMes to "検索結果100件超です(" & numQueryCnt & "件)\r継続すると結果表示まで約:" & numMin & "秒かかります" as text
  try
    set recordResponse to (display alert ("【選んでください】\r" & strAlertMes) buttons {"継続", "終了"} default button "継続" cancel button "終了" as informational giving up after 10) as record
  on error
    log "エラーしました"
return "キャンセルしました。処理を中止します。再度実行してください"
  end try
  if true is equal to (gave up of recordResponse) then
return "時間切れです。処理を中止します。再度実行してください"
  end if
else if numQueryCnt = 0 then
  log "検索結果0件です"
end if
####処理継続の場合はそのまま進む
if (numMach as integer) = 1 then
  set strCommandText to ("/usr/bin/sqlite3 \"" & strDbFilePathURL & "\" -tabs \"SELECT * FROM postalcode WHERE prefecture_kana LIKE '%" & strSearchText & "%' OR city_kana LIKE '%" & strSearchText & "%' OR town_kana LIKE '%" & strSearchText & "%';\"") as text
  log strCommandText
else
  set strCommandText to ("/usr/bin/sqlite3 \"" & strDbFilePathURL & "\" -tabs \"SELECT * FROM postalcode WHERE prefecture LIKE '%" & strSearchText & "%' OR city LIKE '%" & strSearchText & "%' OR town LIKE '%" & strSearchText & "%' OR pref_and_city LIKE '%" & strSearchText & "%';\"") as text
  log strCommandText
end if
set strResponse to (do shell script strCommandText) as text


########################################
##コマンドの戻り値を改行でリストに
set AppleScript's text item delimiters to "\r"
set listResponse to every text item of strResponse
set AppleScript's text item delimiters to ""

########################################
##HTML 基本構造
###スタイル
set strStylle to "<style>#bordertable {padding: 10px;width: 100%;margin: 0;border-collapse: collapse;border-spacing: 0;word-wrap: break-word;} #bordertable table { width: 80%;margin: 0px;padding: 0px;border: 0px;border-spacing:0px;border-collapse: collapse;} #bordertable caption { font-weight: 900;} #bordertable thead { font-weight: 600;border-spacing:0px;} #bordertable td {border: solid 1px #666666;padding: 5px;margin: 0px;word-wrap: break-word;border-spacing:0px;} #bordertable tr {border: solid 1px #666666;padding: 0px;margin: 0px;border-spacing:0px;} #bordertable th {border: solid 1px #666666;padding: 0px;margin: 0px;border-spacing:0px;}</style>"
###ヘッダー部
set strHead to "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>[検索語句]" & strSearchText & "</title>" & strStylle & "</head><body>"
###ボディ
set strBody to ""
###最後
set strHtmlEndBody to "</body></html>"
###HTML書き出し用のテキスト初期化
set ocidHTMLString to refMe's NSMutableString's alloc()'s initWithCapacity:0
####
(ocidHTMLString's appendString:strHead)
#########
###テーブルの開始部
set strHTML to ("<div id=\"bordertable\"><table><caption title=\"タイトル\">検索結果:" & strReturnedText & "</caption>") as text
set strHTML to (strHTML & "<thead title=\"項目名称\"><tr><th title=\"項目1\" scope=\"row\" > 連番 </th><th title=\"項目2\" scope=\"col\"> 郵便番号 </th><th title=\"項目3\" scope=\"col\"> 住所 </th><th title=\"項目4\" scope=\"col\"> 読み </th><th title=\"項目5\" scope=\"col\">団体コード</th><th title=\"項目6\" scope=\"col\">リンク</th></tr></thead><tbody title=\"検索結果一覧\" >") as text
(ocidHTMLString's appendString:(strHTML))
set numLineNo to 1 as integer
repeat with itemLine in listResponse
  ###各行タブ区切りなのでタブでリストにする
  set AppleScript's text item delimiters to "\t"
  set listLineText to every text item of itemLine
  set AppleScript's text item delimiters to ""
  ###必要な項目を取得
  set strCityCode to (item 1 of listLineText) as text
  set strPostNo to (item 3 of listLineText) as text
  set strAddText to ((item 7 of listLineText) & (item 8 of listLineText) & (item 9 of listLineText)) as text
  set strKana to ((item 4 of listLineText) & (item 5 of listLineText) & (item 6 of listLineText)) as text
  ###リンク生成
  set strLinkURL to ("https://www.post.japanpost.jp/cgi-zip/zipcode.php?zip=" & strPostNo & "")
  set strMapURL to ("https://www.google.com/maps/search/郵便番号+" & strPostNo & "")
  set strMapAppURL to ("http://maps.apple.com/?q=郵便番号+" & strPostNo & "")
  set strLINK to "<a href=\"" & strLinkURL & "\" target=\"_blank\">郵政</a>&nbsp;|&nbsp;<a href=\"" & strMapURL & "\" target=\"_blank\">Google</a>&nbsp;|&nbsp;<a href=\"" & strMapAppURL & "\" target=\"_blank\">Map</a>"
  ###HTMLにして
  set strHTML to ("<tr><th title=\"項番1\" scope=\"row\">" & numLineNo & "</th><td title=\"項目2\"><b>" & strPostNo & "</b></td><td title=\"項目3\">" & strAddText & "</td><td title=\"項目4\"><small>" & strKana & "</small></td><td title=\"項目5\">" & strCityCode & "</td><td title=\"項目6\">" & strLINK & "</td></tr>") as text
(ocidHTMLString's appendString:(strHTML))
  set numLineNo to numLineNo + 1 as integer
end repeat

set strHTML to ("</tbody><tfoot><tr><th colspan=\"6\" title=\"フッター表の終わり\" scope=\"row\">post.japanpost.jp</th></tr></tfoot></table></div>") as text
####テーブルまでを追加
(ocidHTMLString's appendString:(strHTML))
####終了部を追加
(ocidHTMLString's appendString:(strHtmlEndBody))

###ディレクトリ
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidTempDirURL to appFileManager's temporaryDirectory()
set ocidUUID to refMe's NSUUID's alloc()'s init()
set ocidUUIDString to ocidUUID's UUIDString
set ocidSaveDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:true
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
###パス

set strFileName to (strSearchText & ".html") as text
set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:false
###ファイルに書き出し
set listDone to ocidHTMLString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
####テキストエディタで開く
set aliasFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias
(*
tell application "TextEdit"
activate
open file aliasFilePath
end tell
*)
tell application "Safari"
  activate
  open file aliasFilePath
end tell






|

郵便番号検索

ダウンロード - 郵便番号検索v1.zip


DB検索 結果をHTMLで表示

【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# DB検索用
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions

property refMe : a reference to current application
property refNSNotFound : a reference to 9.22337203685477E+18 + 5807


#############################
###DBファイルへのパス
tell application "Finder"
  set aliasPathToMe to (path to me) as alias
  set aliasContainerDirPath to (container of aliasPathToMe) as alias
end tell
set strContainerDirPath to (POSIX path of aliasContainerDirPath) as text
set ocidContainerDirPathStr to refMe's NSString's stringWithString:(strContainerDirPath)
set ocidContainerDirPath to ocidContainerDirPathStr's stringByStandardizingPath()
set ocidContainerDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidContainerDirPath) isDirectory:true)
set ocidDBFilePathURL to ocidContainerDirPathURL's URLByAppendingPathComponent:("bin/data/postno.db")
set strDbFilePathURL to (ocidDBFilePathURL's |path|()) as text
#############################
### クリップボードの中身取り出し
###初期化
set ocidPasteboard to refMe's NSPasteboard's generalPasteboard()
set ocidPastBoardTypeArray to ocidPasteboard's types
###テキストがあれば
set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
if boolContain = true then
  ###値を格納する
  tell application "Finder"
    set strReadString to (the clipboard as text) as text
  end tell
  ###Finderでエラーしたら
else
  set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
  if boolContain = true then
    set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
    set strReadString to ocidReadString as text
  else
    log "テキストなし"
    set strReadString to "" as text
  end if
end if
##############################
###ダイアログ
tell current application
  set strName to name as text
end tell
####スクリプトメニューから実行したら
if strName is "osascript" then
  tell application "Finder"
    activate
  end tell
else
  tell current application
    activate
  end tell
end if
set strMes to ("住所で検索 一部分でも可\r神奈川とかで指定すると検索結果が多くなります")
set aliasIconPath to POSIX file "/System/Applications/Calculator.app/Contents/Resources/AppIcon.icns" as alias
try
  set recordResult to (display dialog strMes with title "郵便番号検索" default answer strReadString buttons {"OK", "キャンセル"} default button "OK" with icon aliasIconPath giving up after 20 without hidden answer) as record
on error
  log "エラーしました"
return
end try

if "OK" is equal to (button returned of recordResult) then
  set strReturnedText to (text returned of recordResult) as text
else if (gave up of recordResult) is true then
return "時間切れです"
else
return "キャンセル"
end if
##############################
###戻り値整形
set ocidResponseText to (refMe's NSString's stringWithString:(strReturnedText))
###タブと改行を除去しておく
set ocidTextM to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
ocidTextM's appendString:(ocidResponseText)
##改行除去
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\n") withString:("")
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\r") withString:("")
##タブ除去
set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\t") withString:("")
##############################
###ひらがなのみの場合はカタカナに
set listRegex to refMe's NSRegularExpression's regularExpressionWithPattern:("^[ぁ-んー]+$") options:(0) |error|:(reference)
set ocidRegex to (item 1 of listRegex)
set ocidTextRange to refMe's NSMakeRange(0, (ocidTextM's |length|()))
log ocidTextRange
set numPach to ocidRegex's numberOfMatchesInString:(ocidTextM) options:0 range:(ocidTextRange)
if (numPach as integer) = 1 then
  set ocidTransform to (refMe's NSStringTransformHiraganaToKatakana)
  set ocidTextM to (ocidTextM's stringByApplyingTransform:(ocidTransform) |reverse|:false)
end if
###数字がなければ全角に
set ocidTransform to (refMe's NSStringTransformFullwidthToHalfwidth)
set ocidTextM to (ocidTextM's stringByApplyingTransform:(ocidTransform) |reverse|:true)
########################################
##カタカナと漢字混在で検索方法が異なる
set listRegex to refMe's NSRegularExpression's regularExpressionWithPattern:("^[ァ-ヶー]+$") options:(0) |error|:(reference)
set ocidRegex to (item 1 of listRegex)
set ocidTextRange to refMe's NSMakeRange(0, (ocidTextM's |length|()))
set numPach to ocidRegex's numberOfMatchesInString:(ocidTextM) options:0 range:(ocidTextRange)
set strSearchText to ocidTextM as text
if (numPach as integer) = 1 then
  set strCommandText to ("/usr/bin/sqlite3 \"" & strDbFilePathURL & "\" -tabs \"SELECT * FROM postalcode WHERE prefecture_kana LIKE '%" & strSearchText & "%' OR city_kana LIKE '%" & strSearchText & "%' OR town_kana LIKE '%" & strSearchText & "%';\"") as text
  log strCommandText
else
  set strCommandText to ("/usr/bin/sqlite3 \"" & strDbFilePathURL & "\" -tabs \"SELECT * FROM postalcode WHERE prefecture LIKE '%" & strSearchText & "%' OR city LIKE '%" & strSearchText & "%' OR town LIKE '%" & strSearchText & "%';\"") as text
  log strCommandText
end if
set strResponse to (do shell script strCommandText) as text


########################################
##
set AppleScript's text item delimiters to "\r"
set listResponse to every text item of strResponse
set AppleScript's text item delimiters to ""

########################################
##HTML 基本構造
###スタイル
set strStylle to "<style>#bordertable {padding: 10px;width: 100%;margin: 0;border-collapse: collapse;border-spacing: 0;word-wrap: break-word;} #bordertable table { width: 80%;margin: 0px;padding: 0px;border: 0px;border-spacing:0px;border-collapse: collapse;} #bordertable caption { font-weight: 900;} #bordertable thead { font-weight: 600;border-spacing:0px;} #bordertable td {border: solid 1px #666666;padding: 5px;margin: 0px;word-wrap: break-word;border-spacing:0px;} #bordertable tr {border: solid 1px #666666;padding: 0px;margin: 0px;border-spacing:0px;} #bordertable th {border: solid 1px #666666;padding: 0px;margin: 0px;border-spacing:0px;}</style>"
###ヘッダー部
set strHead to "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>[検索語句]" & strSearchText & "</title>" & strStylle & "</head><body>"
###ボディ
set strBody to ""
###最後
set strHtmlEndBody to "</body></html>"
###HTML書き出し用のテキスト初期化
set ocidHTMLString to refMe's NSMutableString's alloc()'s initWithCapacity:0
####
(ocidHTMLString's appendString:strHead)
#########
###テーブルの開始部
set strHTML to ("<div id=\"bordertable\"><table><caption title=\"タイトル\">検索結果:" & strReturnedText & "</caption>") as text
set strHTML to (strHTML & "<thead title=\"項目名称\"><tr><th title=\"項目1\" scope=\"row\" > 連番 </th><th title=\"項目2\" scope=\"col\"> 郵便番号 </th><th title=\"項目3\" scope=\"col\"> 住所 </th><th title=\"項目4\" scope=\"col\"> 読み </th><th title=\"項目5\" scope=\"col\">団体コード</th><th title=\"項目6\" scope=\"col\">リンク</th></tr></thead><tbody title=\"検索結果一覧\" >") as text
set numLineNo to 1 as integer
repeat with itemLine in listResponse
  set AppleScript's text item delimiters to "\t"
  set listLineText to every text item of itemLine
  set AppleScript's text item delimiters to ""
  
  set strCityCode to (item 1 of listLineText) as text
  set strPostNo to (item 3 of listLineText) as text
  set strAddText to ((item 7 of listLineText) & (item 8 of listLineText) & (item 9 of listLineText)) as text
  set strKana to ((item 4 of listLineText) & (item 5 of listLineText) & (item 6 of listLineText)) as text
  
  set strLinkURL to ("https://www.post.japanpost.jp/cgi-zip/zipcode.php?zip=" & strPostNo & "")
  set strMapURL to ("https://www.google.com/maps/search/郵便番号+" & strPostNo & "")
  set strMapAppURL to ("http://maps.apple.com/?q=郵便番号+" & strPostNo & "")
  set strLINK to "<a href=\"" & strLinkURL & "\" target=\"_blank\">郵政</a>&nbsp;|&nbsp;<a href=\"" & strMapURL & "\" target=\"_blank\">Google</a>&nbsp;|&nbsp;<a href=\"" & strMapAppURL & "\" target=\"_blank\">Map</a>"
  
  set strHTML to (strHTML & "<tr><th title=\"項番1\" scope=\"row\">" & numLineNo & "</th><td title=\"項目2\"><b>" & strPostNo & "</b></td><td title=\"項目3\">" & strAddText & "</td><td title=\"項目4\"><small>" & strKana & "</small></td><td title=\"項目5\">" & strCityCode & "</td><td title=\"項目6\">" & strLINK & "</td></tr>") as text
  
  set numLineNo to numLineNo + 1 as integer
end repeat


set strHTML to (strHTML & "</tbody><tfoot><tr><th colspan=\"6\" title=\"フッター表の終わり\" scope=\"row\">post.japanpost.jp</th></tr></tfoot></table></div>") as text
####テーブルまでを追加
(ocidHTMLString's appendString:(strHTML))
####終了部を追加
(ocidHTMLString's appendString:(strHtmlEndBody))

###ディレクトリ
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidTempDirURL to appFileManager's temporaryDirectory()
set ocidUUID to refMe's NSUUID's alloc()'s init()
set ocidUUIDString to ocidUUID's UUIDString
set ocidSaveDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:true
set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0
# 777-->511 755-->493 700-->448 766-->502
ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions)
set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error|:(reference)
###パス

set strFileName to (strSearchText & ".html") as text
set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:false
###ファイルに書き出し
set listDone to ocidHTMLString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
####テキストエディタで開く
set aliasFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias
(*
tell application "TextEdit"
activate
open file aliasFilePath
end tell
*)
tell application "Safari"
  activate
  open file aliasFilePath
end tell

DB作成

【スクリプトエディタで開く】|

#!/bin/bash
#com.cocolog-nifty.quicktimer.icefloe
##################################################
###設定項目 CSVのファイル名
STR_CSV_FILE_NAME="utf_all.csv"
### path to me
SCRIPT_PATH="${BASH_SOURCE[0]}"
/bin/echo "このスクリプトのパス $SCRIPT_PATH"
STR_CONTAINER_DIR_PATH=$(/usr/bin/dirname "$SCRIPT_PATH")
/bin/echo "コンテナディレクトリ $STR_CONTAINER_DIR_PATH"
STR_DATA_DIR_PATH="$STR_CONTAINER_DIR_PATH/data"
/bin/mkdir -p "$STR_DATA_DIR_PATH"
/bin/echo "データ格納ディレクトリ $STR_DATA_DIR_PATH"
STR_CSV_FILE_PATH="$STR_DATA_DIR_PATH/$STR_CSV_FILE_NAME"
/bin/echo "CSVのファイルパス $STR_CSV_FILE_PATH"
STR_IMPORT_FILE_PATH="$STR_DATA_DIR_PATH/$STR_CSV_FILE_NAME.import.csv"
/bin/echo "SQLインポート用CSVの書き出しパス $STR_IMPORT_FILE_PATH"
STR_DB_FILE_PATH="$STR_DATA_DIR_PATH/postno.db"
/bin/echo "SQLDBのパス $STR_DB_FILE_PATH"
##################################################
###古いデータは削除する
/usr/bin/touch "$STR_IMPORT_FILE_PATH"
/usr/bin/touch "$STR_DB_FILE_PATH"
/usr/bin/touch "$STR_CSV_FILE_PATH"
/bin/rm  "$STR_IMPORT_FILE_PATH"
/bin/rm  "$STR_DB_FILE_PATH"
/bin/rm  "$STR_CSV_FILE_PATH"
##################################################
STR_URL="https://www.post.japanpost.jp/zipcode/dl/utf/zip/utf_all.zip"
###ダウンロード起動時に削除する項目
USER_TEMP_DIR=$(/usr/bin/mktemp -d)
/bin/echo "起動時に削除されるディレクトリ $USER_TEMP_DIR"
if ! /usr/bin/curl -L -o "$USER_TEMP_DIR/utf_all.zip" "$STR_URL" --connect-timeout 20; then
  /bin/echo "ファイルのダウンロードに失敗しました HTTP1.1で再トライします"
  if ! /usr/bin/curl -L -o "$USER_TEMP_DIR/utf_all.zip" "$STR_URL" --http1.1 --connect-timeout 20; then
    /bin/echo "ファイルのダウンロードに失敗しました"
    exit 1
  fi
fi
/bin/echo "ダウンロードしたZIPファイル $USER_TEMP_DIR/utf_all.zip"
##################################################
###解凍
/usr/bin/cd "$STR_DATA_DIR_PATH"
/usr/bin/bsdtar -xzvf "$USER_TEMP_DIR/utf_all.zip" -C "$STR_DATA_DIR_PATH"
/bin/echo "ダウンロードデータ解凍OK"
##################################################
###クオテーション除去
STR_TMP_FILE_PATH="$USER_TEMP_DIR/$STR_CSV_FILE_NAME.tmp.csv"
/usr/bin/sed 's/"//g' "$STR_CSV_FILE_PATH" > "$STR_TMP_FILE_PATH"
###改行変更
/usr/bin/sed 's/\r$//' "$STR_TMP_FILE_PATH" > "$STR_IMPORT_FILE_PATH"
/bin/echo "データ整形終了"
##################################################
###1行目挿入 この処理は不要だった
## STR_HEADER_TEXT="code,old_no,p_no,prefecture_kana,city_kana,town_kana,prefecture,city,town,more,aza,cho,contain,update,change"
## /usr/bin/touch "$STR_IMPORT_FILE_PATH"
## /bin/echo "$STR_HEADER_TEXT" > "$STR_IMPORT_FILE_PATH"
## /bin/cat "$STR_TMPB_FILE_PATH" >> "$STR_IMPORT_FILE_PATH"
##################################################
/bin/echo "データインポート開始"
###インポート DB作成
/usr/bin/sqlite3 "$STR_DB_FILE_PATH" <<EOF
CREATE TABLE postalcode (code TEXT,old_no TEXT,p_no TEXT,prefecture_kana TEXT,city_kana TEXT,town_kana TEXT,prefecture TEXT,city TEXT,town TEXT,more INTEGER,azamore INTEGER,chomore INTEGER,containmore INTEGER,updatemore INTEGER,changemore INTEGER);
.mode csv
.import "$STR_IMPORT_FILE_PATH" postalcode
EOF
/bin/echo "データインポート終了"
/bin/echo "処理終了しました"
exit 0


|

その他のカテゴリー

Accessibility Acrobat Acrobat 2020 Acrobat AddOn Acrobat Annotation Acrobat ARMDC Acrobat AV2 Acrobat BookMark Acrobat Classic Acrobat DC Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat JS Acrobat Manifest Acrobat Menu Acrobat Open Acrobat Plugin Acrobat Preferences Acrobat Preflight Acrobat python Acrobat Reader Acrobat SCA Acrobat SCA Updater Acrobat Sequ Acrobat Sign Acrobat Stamps Acrobat Watermark Acrobat Windows Acrobat Windows Reader Admin Admin Account Admin Apachectl Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Mobileconfig Admin Permission Admin Pkg Admin Power Management Admin Printer Admin SetUp Admin SMB Admin Support Admin System Information Admin Tools Admin Users Admin Volumes Adobe Adobe FDKO Adobe RemoteUpdateManager AppKit Apple AppleScript AppleScript do shell script AppleScript List AppleScript ObjC AppleScript Osax AppleScript PDF AppleScript Pictures AppleScript record AppleScript Script Editor AppleScript Script Menu AppleScript Shortcuts AppleScript Shortcuts Events AppleScript System Events AppleScript System Events Plist AppleScript Video Applications AppStore Archive Attributes Automator BackUp Barcode Barcode QR Barcode QR Decode Bash Basic Basic Path Bluetooth BOX Browser Calendar CD/DVD Choose Chrome CIImage CityCode CloudStorage Color com.apple.LaunchServices.OpenWith Console Contacts CotEditor CURL current application Date&Time delimiters Desktop Device Diff Disk Dock DropBox Droplet eMail Encode % Encode Decode Encode UTF8 Error EXIFData ffmpeg File Finder Firefox Folder FolderAction Fonts GIF github Guide HTML HTML Entity Icon Illustrator Image Events Image2PDF ImageOptim iPhone iWork Javascript Jedit Json Label Leading Zero List locationd LRC lsappinfo LSSharedFileList m3u8 Mail MakePDF Map Math Media Media AVAsset Media AVconvert Media AVFoundation Media AVURLAsset Media Movie Media Music Memo Messages Microsoft Microsoft Edge Microsoft Excel Mouse Music NetWork Notes NSArray NSArray Sort NSBezierPath NSBitmapImageRep NSBundle NSCFBoolean NSCharacterSet NSColor NSColorList NSData NSDecimalNumber NSDictionary NSError NSEvent NSFileAttributes NSFileManager NSFileManager enumeratorAtURL NSFont NSFontManager NSGraphicsContext NSImage NSIndex NSKeyedArchiver NSKeyedUnarchiver NSLocale NSMutableArray NSMutableDictionary NSMutableString NSNotFound NSNumber NSOpenPanel NSPasteboard NSpoint NSPredicate NSPrintOperation NSRange NSRect NSRegularExpression NSRunningApplication NSScreen NSSize NSString NSString stringByApplyingTransform NSStringCompareOptions NSTask NSTimeZone NSURL NSURL File NSURLBookmark NSURLComponents NSURLResourceKey NSURLSession NSUserDefaults NSUUID NSView NSWorkspace Numbers OAuth OneDrive PDF PDFAnnotation PDFAnnotationWidget PDFContext PDFDisplayBox PDFDocumentPermissions PDFImageRep PDFKit PDFnUP PDFOutline perl Photoshop PlistBuddy pluginkit postalcode PostScript prefPane Preview Python QuickLook QuickTime ReadMe Regular Expression Reminders ReName Repeat RTF Safari SaveFile ScreenCapture ScreenSaver SF Symbols character id SF Symbols Entity sips Skype Slack Sound Spotlight sqlite SRT StandardAdditions Swift System Settings TCC TemporaryItems Terminal Text Text CSV Text MD Text TSV TextEdit Tools Translate Trash Twitter Typography UI Unit Conversion UTType valueForKeyPath Video VisionKit Visual Studio Code VMware Fusion Wacom webarchive webp Wifi Windows XML XML EPUB XML OPML XML Plist XML RSS XML savedSearch XML SVG XML TTML XML webloc XML XMP YouTube zoom