AppleScript Text TSV

TSV2HTML TSVタブ区切りテキストをHTMLテーブルにする(少し修正)


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
(*
com.cocolog-nifty.quicktimer.icefloe
TSV2HTML項番あり

*)
----+----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


##設定項目
set strHeaderH3Text to ("SystemStats一覧") as text
set strArticleH3Text to ("SystemStatsコマンドで収集したデータ") as text
set strCaptionText to ("SystemStats") as text


### 【1】入力ファイル
#ダイアログ
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.tab-separated-values-text"}
set strMes to ("ファイルを選んでください") as text
set strPrompt to ("ファイルを選んでください") as text
try
  ### ファイル選択時
  set aliasFilePath to (choose file strMes with prompt strPrompt default location aliasDesktopDirPath of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
if aliasFilePath is (missing value) then
return "選んでください"
end if
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 ocidFileName to ocidBaseFilePathURL's lastPathComponent()
set ocidSaveFilePathURL to (ocidBaseFilePathURL's URLByAppendingPathExtension:("html"))
### 【2】 ファイルのテキストを読み込み
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 ocidLineString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
(ocidLineString's setString:(ocidReadString))
#改行をUNIXに強制
set ocidLineStringLF to (ocidLineString's stringByReplacingOccurrencesOfString:("\r\n") withString:("\n"))
set ocidLineString to (ocidLineStringLF's stringByReplacingOccurrencesOfString:("\r") withString:("\n"))
#改行毎でリストにする
set ocidCharSet to (refMe's NSCharacterSet's newlineCharacterSet)
set ocidLineArray to (ocidLineString's componentsSeparatedByCharactersInSet:(ocidCharSet))
#最初の1行目だけ別で取得しておく
set ocidFirstObjectString to ocidLineArray's firstObject()
set ocidFirstLineArray to ocidFirstObjectString's componentsSeparatedByString:("\t")

###【4】データをHTMLに整形
########################################
#headerに渡すエレメント
set ocidSetHeaderElement to (refMe's NSXMLElement's elementWithName:("div"))
set ocidH3Element to refMe's NSXMLElement's elementWithName:("h3")
(ocidH3Element's setStringValue:(strHeaderH3Text))
(ocidSetHeaderElement's addChild:(ocidH3Element))

########################################
#footerに渡すエレメント
set ocidSetFooterElement to (refMe's NSXMLElement's elementWithName:("div"))
set ocidAElement to refMe's NSXMLElement's elementWithName:("a")
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("href") stringValue:("https://quicktimer.cocolog-nifty.com/"))
(ocidAElement's addAttribute:(ocidAddNode))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("target") stringValue:("_blank"))
(ocidAElement's addAttribute:(ocidAddNode))
set strContents to ("AppleScriptで生成しました") as text
(ocidAElement's setStringValue:(strContents))
(ocidSetFooterElement's addChild:(ocidAElement))

########################################
#articleに渡すエレメント
set ocidSetArticleElement to (refMe's NSXMLElement's elementWithName:("div"))
set ocidH3Element to (refMe's NSXMLElement's elementWithName:("h3"))
set strSetValue to (strArticleH3Text) as text
(ocidH3Element's setStringValue:(strSetValue))
(ocidSetArticleElement's addChild:(ocidH3Element))


#テーブル部生成開始
set ocidTableElement to refMe's NSXMLElement's elementWithName:("table")
#【caption】
set ocidCaptionElement to refMe's NSXMLElement's elementWithName:("caption")
ocidCaptionElement's setStringValue:(strCaptionText)
ocidTableElement's addChild:(ocidCaptionElement)
#【colgroup】
set ocidColgroupElement to refMe's NSXMLElement's elementWithName:("colgroup")
#タイトル部の数だけ繰り返し
#項番部を追加する
set strFirstCol to ("LineNo") as text
ocidFirstLineArray's insertObject:(strFirstCol) atIndex:(0)
repeat with itemColName in ocidFirstLineArray
  #【col】col生成
  set ocidAddElement to (refMe's NSXMLElement's elementWithName:("col"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
(ocidColgroupElement's addChild:(ocidAddElement))
end repeat
#テーブルエレメントに追加
ocidTableElement's addChild:(ocidColgroupElement)
#【thead】
set ocidTheadElement to refMe's NSXMLElement's elementWithName:("thead")
#TR
set ocidTrElement to refMe's NSXMLElement's elementWithName:("tr")
#タイトル部の数だけ繰り返し
repeat with itemColName in ocidFirstLineArray
  if (itemColName as text) is "LineNo" then
    #ここはTDではなくてTHを利用
    set ocidAddElement to (refMe's NSXMLElement's elementWithName:("th"))
    ####項番処理
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
    #
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("id") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("col"))
(ocidAddElement's addAttribute:(ocidAddNode))
    #値を入れる
(ocidAddElement's setStringValue:("\"))
    #TH→TRにセット
(ocidTrElement's addChild:(ocidAddElement))
  else
    #ここはTDではなくてTHを利用
    set ocidAddElement to (refMe's NSXMLElement's elementWithName:("th"))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
    #
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("id") stringValue:(itemColName))
(ocidAddElement's addAttribute:(ocidAddNode))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("col"))
(ocidAddElement's addAttribute:(ocidAddNode))
    #値を入れる
(ocidAddElement's setStringValue:(itemColName))
    #TH→TRにセット
(ocidTrElement's addChild:(ocidAddElement))
  end if
end repeat
#TRをTHEADにセット
ocidTheadElement's addChild:(ocidTrElement)
#THEADをテーブルにセット
ocidTableElement's addChild:(ocidTheadElement)
########################################
#【tbody】
set ocidTbodyElement to refMe's NSXMLElement's elementWithName:("tbody")
###【3-4】:item
set numCntContents to (count of ocidLineArray) - 1 as integer
repeat with itemIntNo from 1 to numCntContents by 1
  set ocidLineItem to (ocidLineArray's objectAtIndex:(itemIntNo))
  #空行で終わり(TSVが改行で終わるタイプ)
  if (ocidLineItem as text) is "" then
    exit repeat
  end if
  #
  set ocidItemLineArray to (ocidLineItem's componentsSeparatedByString:("\t"))
  set numCntItemLineArray to (count of ocidItemLineArray) as integer
  ##############
  #TRの開始
  set ocidTrElement to (refMe's NSXMLElement's elementWithName:("tr"))
  ####項番処理
  set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("項目番号:" & itemIntNo))
(ocidThElement's addAttribute:(ocidAddNode))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("headers") stringValue:("LineNo"))
(ocidThElement's addAttribute:(ocidAddNode))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("col"))
(ocidThElement's addAttribute:(ocidAddNode))
(ocidThElement's setStringValue:(itemIntNo as text))
(ocidTrElement's addChild:(ocidThElement))
  
  repeat with itemLineNo from 0 to (numCntItemLineArray - 1) by 1
    set coidFieldValue to (ocidItemLineArray's objectAtIndex:(itemLineNo))
    if itemLineNo = 0 then
      set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
      set strTitle to (ocidFirstLineArray's objectAtIndex:(itemLineNo + 1))
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(strTitle))
(ocidThElement's addAttribute:(ocidAddNode))
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("headers") stringValue:(strTitle))
(ocidThElement's addAttribute:(ocidAddNode))
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("col"))
(ocidThElement's addAttribute:(ocidAddNode))
(ocidThElement's setStringValue:(coidFieldValue))
(ocidTrElement's addChild:(ocidThElement))
    else
      set ocidTdElement to (refMe's NSXMLElement's elementWithName:("td"))
      set strTitle to (ocidFirstLineArray's objectAtIndex:(itemLineNo + 1))
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:(strTitle))
(ocidTdElement's addAttribute:(ocidAddNode))
      set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("headers") stringValue:(strTitle))
(ocidTdElement's addAttribute:(ocidAddNode))
(ocidTdElement's setStringValue:(coidFieldValue))
(ocidTrElement's addChild:(ocidTdElement))
    end if
  end repeat
(ocidTbodyElement's addChild:(ocidTrElement))
end repeat
#TBODYをテーブルにセット
ocidTableElement's addChild:(ocidTbodyElement)
#【tfoot】 TRで
set ocidTfootElement to refMe's NSXMLElement's elementWithName:("tfoot")
set ocidTrElement to refMe's NSXMLElement's elementWithName:("tr")
#項目数を取得して
set numCntCol to (count of ocidFirstLineArray) as integer
#colspan指定して1行でセット
set ocidThElement to (refMe's NSXMLElement's elementWithName:("th"))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("title") stringValue:("テーブルの終わり"))
(ocidThElement's addAttribute:(ocidAddNode))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("colspan") stringValue:(numCntCol as text))
(ocidThElement's addAttribute:(ocidAddNode))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("scope") stringValue:("row"))
(ocidThElement's addAttribute:(ocidAddNode))
#
set strContents to ("項目数 : " & (numCntContents - 1)) as text
(ocidThElement's setStringValue:(strContents))
#THをTRにセットして
ocidTrElement's addChild:(ocidThElement)
#TRをTFOOTにセット
ocidTfootElement's addChild:(ocidTrElement)
#TFOOTをテーブルにセット
ocidTableElement's addChild:(ocidTfootElement)
#テーブルをアーティクルにセット
ocidSetArticleElement's addChild:(ocidTableElement)
##############################
#HTMLにする
##############################
set ocidHTML to doMakeRootElement({ocidSetHeaderElement, ocidSetArticleElement, ocidSetFooterElement})

##############################
#保存
##############################

#####【5−2】保存
#読み取りやすい表示
set ocidXMLdata to ocidHTML's XMLDataWithOptions:(refMe's NSXMLNodePrettyPrint)

set listDone to ocidXMLdata's writeToURL:(ocidSaveFilePathURL) options:(refMe's NSDataWritingAtomic) |error|:(reference)

####【6】ブラウザで開く
set aliasFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias
tell application "Finder"
open location aliasFilePath
end tell

############################################################
# 基本的なHTMLの構造
(*
doMakeRootElement({argHeaderContents, argArticleContents, argFooterContents})
HTMLのBODY部
header
article
footerにそれぞれAddchildするデータをリストで渡す
戻り値はRootエレメントにセットされた
NSXMLDocumentを戻すので 保存すればOK
*)
############################################################
to doMakeRootElement({argHeaderContents, argArticleContents, argFooterContents})
  #XML初期化
  set ocidXMLDoc to refMe's NSXMLDocument's alloc()'s init()
ocidXMLDoc's setDocumentContentKind:(refMe's NSXMLDocumentHTMLKind)
  # DTD付与
  set ocidDTD to refMe's NSXMLDTD's alloc()'s init()
ocidDTD's setName:("html")
ocidXMLDoc's setDTD:(ocidDTD)
  #
  set ocidRootElement to refMe's NSXMLElement's elementWithName:("html")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("lang") stringValue:("ja")
ocidRootElement's addAttribute:(ocidAddNode)
  #
  set ocidHeadElement to refMe's NSXMLElement's elementWithName:("head")
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("title")
ocidAddElement's setStringValue:("TSV2HTML")
ocidHeadElement's addChild:(ocidAddElement)
  # http-equiv
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/html; charset=UTF-8")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Style-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/css")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("http-equiv") stringValue:("Content-Script-Type")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("text/javascript")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("meta")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("name") stringValue:("viewport")
ocidAddElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("content") stringValue:("width=720")
ocidAddElement's addAttribute:(ocidAddNode)
ocidHeadElement's addChild:(ocidAddElement)
  #
  set ocidAddElement to refMe's NSXMLElement's elementWithName:("style")
ocidAddElement's setStringValue:("body { margin: 10px; background-color: #FFFFFF; } table { border-spacing: 0; caption-side: top; font-family: system-ui; } thead th { border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; &:first-of-type { border-start-start-radius: .5em } &:last-of-type { border-start-end-radius: .5em; border-inline-end-width: 1px } } tbody td { word-wrap: break-word;max-width: 360px;border-spacing: 0; border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; &:last-of-type { border-inline-end-width: 1px } } tbody th { border-spacing: 0; border: solid 1px #666666; padding: .5ch 1ch; border-block-width: 1px 0; border-inline-width: 1px 0; } tbody tr:nth-of-type(odd) { background: #F2F2F2; } .kind_string { font-size: 0.75em; } .date_string { font-size: 0.5em; } tfoot th { border: solid 1px #666666; padding: .5ch 1ch; &:first-of-type { border-end-start-radius: .5em } &:last-of-type { border-end-end-radius: .5em; border-inline-end-width: 1px } }")
ocidHeadElement's addChild:(ocidAddElement)
ocidRootElement's addChild:(ocidHeadElement)
  #
  #ボディエレメント
  set ocidBodyElement to refMe's NSXMLElement's elementWithName:("body")
  #ヘッダー
  set ocidHeaderElement to refMe's NSXMLElement's elementWithName:("header")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("header")
ocidHeaderElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_header")
ocidHeaderElement's addAttribute:(ocidAddNode)
ocidHeaderElement's addChild:(argHeaderContents)
ocidBodyElement's addChild:(ocidHeaderElement)
  #アーティクル
  set ocidArticleElement to refMe's NSXMLElement's elementWithName:("article")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("article")
ocidArticleElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_article")
ocidArticleElement's addAttribute:(ocidAddNode)
ocidArticleElement's addChild:(argArticleContents)
ocidBodyElement's addChild:(ocidArticleElement)
  #フッター
  set ocidFooterElement to refMe's NSXMLElement's elementWithName:("footer")
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("id") stringValue:("footer")
ocidFooterElement's addAttribute:(ocidAddNode)
  set ocidAddNode to refMe's NSXMLNode's attributeWithName:("class") stringValue:("body_footer")
ocidFooterElement's addAttribute:(ocidAddNode)
ocidFooterElement's addChild:(argFooterContents)
ocidBodyElement's addChild:(ocidFooterElement)
  #ボディをROOTエレメントにセット
ocidRootElement's addChild:(ocidBodyElement)
  #ROOTをXMLにセット
ocidXMLDoc's setRootElement:(ocidRootElement)
  #値を戻す
return ocidXMLDoc
end doMakeRootElement

|

TSV行列入替


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


################################
#### TSV行列入替
################################
to doChgColRowTSV(argNSString)
  #可変にして
  set ocidLineString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
(ocidLineString's setString:(ocidReadString))
  #改行をUNIXに強制
  set ocidLineStringLF to (ocidLineString's stringByReplacingOccurrencesOfString:("\r\n") withString:("\n"))
  set ocidLineString to (ocidLineStringLF's stringByReplacingOccurrencesOfString:("\r") withString:("\n"))
  #改行毎でリストにする
  set ocidCharSet to (refMe's NSCharacterSet's newlineCharacterSet)
  set ocidTextArray to (ocidLineString's componentsSeparatedByCharactersInSet:(ocidCharSet))
  #リストの数
  set numCntArray to (count of ocidTextArray) as integer
  #出力用のテキスト
  set ocidSaveString to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
  set ocidColArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
  #1行目のテキストを取り出して
  set ocidFirsText to ocidTextArray's firstObject()
  #タブ区切りテキストにする
  set ocidFirstRowArray to ocidFirsText's componentsSeparatedByString:("\t")
  #1行目のリストの数
  set numCntFirstArray to (count of ocidFirstRowArray) as integer
  #2行目からの処理
  repeat with itemRowNo from 0 to (numCntFirstArray - 1) by 1
    #まずは1行目のデータを取り出して
    set ocidFirstItemText to (ocidFirstRowArray's objectAtIndex:(itemRowNo))
    #出力用テキストに追加しておく
(ocidSaveString's appendString:(ocidFirstItemText))
(ocidSaveString's appendString:("\t"))
    #2列目以降のデータを順に取り出して
    repeat with itemColNo from 1 to (numCntArray - 1) by 1
      #2行目以降を順番に取り出して
      set ocidLineText to (ocidTextArray's objectAtIndex:(itemColNo))
      #リストにする
      set ocidRowArray to (ocidLineText's componentsSeparatedByString:("\t"))
      #対象の列の値を取り出して
      set ocidLineItemText to (ocidRowArray's objectAtIndex:(itemRowNo))
      #追加していく
(ocidSaveString's appendString:(ocidLineItemText))
      #最後のデータにはタブ入れない
      if itemColNo < (numCntArray - 1) then
(ocidSaveString's appendString:("\t"))
      end if
    end repeat
(ocidSaveString's appendString:("\n"))
  end repeat
return ocidSaveString
end doChgColRowTSV



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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
# TSVファイルの行列を入れ替えます
# 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

#############################
###ダイアログを前面に出す
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 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 aliasDefaultLocation to (ocidDesktopDirPathURL's absoluteURL()) as alias

############UTIリスト
set listUTI to {"public.tab-separated-values-text"}
set strMes to ("ファイルを選んでください") as text
set strPrompt to ("ファイルを選んでください") as text
try
  ### ファイル選択時
  set aliasFilePath to (choose file strMes with prompt strPrompt default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
##入力ファイルパス
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)
if (item 2 of listDone) ≠ (missing value) then
  set strErrorMes to (item 2 of listDone)'s localizedDescription() as text
return "エラーが発生しました" & strErrorMes
end if
#可変にして
set ocidLineString to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
(ocidLineString's setString:(ocidReadString))
#改行をUNIXに強制
set ocidLineStringLF to (ocidLineString's stringByReplacingOccurrencesOfString:("\r\n") withString:("\n"))
set ocidLineString to (ocidLineStringLF's stringByReplacingOccurrencesOfString:("\r") withString:("\n"))
#改行毎でリストにする
set ocidCharSet to (refMe's NSCharacterSet's newlineCharacterSet)
set ocidTextArray to (ocidLineString's componentsSeparatedByCharactersInSet:(ocidCharSet))
#リストの数
set numCntArray to (count of ocidTextArray) as integer
#出力用のテキスト
set ocidSaveString to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
set ocidColArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
#1行目のテキストを取り出して
set ocidFirsText to ocidTextArray's firstObject()
#タブ区切りテキストにする
set ocidFirstRowArray to ocidFirsText's componentsSeparatedByString:("\t")
#1行目のリストの数
set numCntFirstArray to (count of ocidFirstRowArray) as integer
#2行目からの処理
repeat with itemRowNo from 0 to (numCntFirstArray - 1) by 1
  #まずは1行目のデータを取り出して
  set ocidFirstItemText to (ocidFirstRowArray's objectAtIndex:(itemRowNo))
  #出力用テキストに追加しておく
(ocidSaveString's appendString:(ocidFirstItemText))
(ocidSaveString's appendString:("\t"))
  #2列目以降のデータを順に取り出して
  repeat with itemColNo from 1 to (numCntArray - 1) by 1
    #2行目以降を順番に取り出して
    set ocidLineText to (ocidTextArray's objectAtIndex:(itemColNo))
    #リストにする
    set ocidRowArray to (ocidLineText's componentsSeparatedByString:("\t"))
    #対象の列の値を取り出して
    set ocidLineItemText to (ocidRowArray's objectAtIndex:(itemRowNo))
    #追加していく
(ocidSaveString's appendString:(ocidLineItemText))
    #最後のデータにはタブ入れない
    if itemColNo < (numCntArray - 1) then
(ocidSaveString's appendString:("\t"))
    end if
  end repeat
(ocidSaveString's appendString:("\n"))
end repeat
#保存
set listDone to ocidSaveString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)

if (item 1 of listDone) is false then
  set strErrorMes to (item 2 of listDone)'s localizedDescription() as text
return "保存に失敗しました" & strErrorMes
end if

|

TSV2AdobeXML タブ区切りテキストからAdobe Illustratorの変数印字用の『変数ライブラリ』を生成する(1ページに複数面付け版)

TSV2AdobeXML タブ区切りテキストからAdobe Illustratorの変数印字用の『変数ライブラリ』を生成する
https://quicktimer.cocolog-nifty.com/icefloe/2024/03/post-bba3c3.html

複数項目を1ページ内に面付けする用

ダウンロード - tsv2adobexml4entries.zip



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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
(*
com.cocolog-nifty.quicktimer.icefloe
TSVタブ区切りテキストから
Adobe Illustrator用の変数用のXMLを生成します

設定項目で1ページに面付けする数を設定してください
デフォルトは10です
-->1ページに10件分のデータを割り付けます

【制限事項】その1
TSVの1行目の項目がデータセット名になります
表の1行目が項目名称になるようなTSVで利用してください
【制限事項】その2
可変テキストのみ設定可能です
他の要素の付与はご相談ください
*)
----+----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
set appFileManager to refMe's NSFileManager's defaultManager()

#################################
### 【1】設定項目
#################################
#1ページの面付け数
set numPageEntries to 10 as integer

#################################
### 【1】入力ファイル
#################################
#ダイアログ
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
#デフォルトロケーション
tell application "Finder"
  set aliasPathToMe to (path to me) as alias
  set aliasContainerDir to (container of aliasPathToMe) as alias
end tell
#
set listUTI to {"public.tab-separated-values-text"}
set strMes to ("ファイルを選んでください") as text
set strPrompt to ("ファイルを選んでください") as text
try
  ### ファイル選択時
  set aliasFilePath to (choose file strMes with prompt strPrompt default location aliasContainerDir of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
if aliasFilePath is (missing value) then
return "選んでください"
end if
#ファイルパス
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)
#################################
### 【2】保存先
#################################
set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
set aliasContainerDirPath to (ocidContainerDirPathURL's absoluteURL()) as alias
set strMes to "フォルダを選んでください" as text
set strPrompt to "保存先フォルダを選択してください\n同名ファイルがある場合\n『上書き』になります" as text
try
  ###ダイアログを前面に出す
  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 aliasResponse to (choose folder strMes with prompt strPrompt default location aliasContainerDirPath with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
#戻り値エイリアスをURLに
set strSaveDirPath to (POSIX path of aliasResponse) as text
set ocidSaveDirPathStr to (refMe's NSString's stringWithString:(strSaveDirPath))
set ocidSaveDirPath to ocidSaveDirPathStr's stringByStandardizingPath()
set ocidSaveDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSaveDirPath) isDirectory:true)
##出力用ファイルパス
set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:("variables.xml")
#################################
### 【3】本処理
#################################
#ファイル読み込み
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
return "文字コードを判定出来ませんでした : " & strFileName
end if

#改行コードをUNIXに強制
set ocidCRChar to refMe's NSString's stringWithString:("\r")
set ocidLFChar to refMe's NSString's stringWithString:("\n")
set ocidCRLFChar to refMe's NSString's stringWithString:("\r\n")
set ocidReadStringsA to ocidReadString's stringByReplacingOccurrencesOfString:(ocidCRLFChar) withString:(ocidLFChar)
set ocidReadStrings to ocidReadStringsA's stringByReplacingOccurrencesOfString:(ocidCRChar) withString:(ocidLFChar)

#改行毎でリストにする
set ocidCharSet to (refMe's NSCharacterSet's newlineCharacterSet)
set ocidLineArray to (ocidReadStrings's componentsSeparatedByCharactersInSet:(ocidCharSet))

#出力用のリスト
set ocidEditLineArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)

#読み取ったデータに項目連番を入れておく
set numCntLineNo to 0 as integer
repeat with itemLineArray in ocidLineArray
  set ocidEditLineText to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
  if numCntLineNo = 0 then
    set strAppendText to ("rowno\t") as text
(ocidEditLineText's appendString:(strAppendText))
(ocidEditLineText's appendString:(itemLineArray))
  else
    if (itemLineArray as text) is "" then
      exit repeat
    end if
    #タブ区切りで挿入
    set strAppendText to (numCntLineNo & "\t") as text
(ocidEditLineText's appendString:(strAppendText))
(ocidEditLineText's appendString:(itemLineArray))
  end if
(ocidEditLineArray's addObject:(ocidEditLineText))
  #カウントアップ
  set numCntLineNo to (numCntLineNo + 1) as integer
end repeat

#最初の1行目だけ別で取得しておく
set ocidFirstObjectString to ocidEditLineArray's firstObject()
set ocidFirstRowArray to ocidFirstObjectString's componentsSeparatedByString:("\t")

################################
###XML初期化
set ocidXMLDoc to refMe's NSXMLDocument's alloc()'s init()
ocidXMLDoc's setVersion:("1.0")
ocidXMLDoc's setCharacterEncoding:("utf-8")
ocidXMLDoc's setDocumentContentKind:(refMe's NSXMLDocumentXMLKind)
###DTD生成
set ocidDTD to refMe's NSXMLDTD's alloc()'s init()
ocidDTD's setName:("svg")
ocidDTD's setPublicID:("-//W3C//DTD SVG 20001102//EN")
ocidDTD's setSystemID:("http://www.w3.org/TR/2000/CR-SVG-20001102/DTD/svg-20001102.dtd")
#Entitry付与
set strEntitry to ("<!ENTITY ns_graphs \"http://ns.adobe.com/Graphs/1.0/\">") as text
set ocidEntitry to refMe's NSString's stringWithString:(strEntitry)
set ocidEntityNode to refMe's NSXMLDTDNode's alloc()'s initWithXMLString:(ocidEntitry)
ocidEntityNode's setDTDKind:(refMe's NSXMLAttributeEntityKind)
ocidDTD's addChild:(ocidEntityNode)
#Entitry付与
set strEntitry to ("<!ENTITY ns_vars \"http://ns.adobe.com/Variables/1.0/\">") as text
set ocidEntitry to refMe's NSString's stringWithString:(strEntitry)
set ocidEntityNode to refMe's NSXMLDTDNode's alloc()'s initWithXMLString:(ocidEntitry)
ocidEntityNode's setDTDKind:(refMe's NSXMLAttributeEntityKind)
ocidDTD's addChild:(ocidEntityNode)
#Entitry付与
set strEntitry to ("<!ENTITY ns_imrep \"http://ns.adobe.com/ImageReplacement/1.0/\">") as text
set ocidEntitry to refMe's NSString's stringWithString:(strEntitry)
set ocidEntityNode to refMe's NSXMLDTDNode's alloc()'s initWithXMLString:(ocidEntitry)
ocidEntityNode's setDTDKind:(refMe's NSXMLAttributeEntityKind)
ocidDTD's addChild:(ocidEntityNode)
#Entitry付与
set strEntitry to ("<!ENTITY ns_custom \"http://ns.adobe.com/GenericCustomNamespace/1.0/\">") as text
set ocidEntitry to refMe's NSString's stringWithString:(strEntitry)
set ocidEntityNode to refMe's NSXMLDTDNode's alloc()'s initWithXMLString:(ocidEntitry)
ocidEntityNode's setDTDKind:(refMe's NSXMLAttributeEntityKind)
ocidDTD's addChild:(ocidEntityNode)
#Entitry付与
set strEntitry to ("<!ENTITY ns_flows \"http://ns.adobe.com/Flows/1.0/\">") as text
set ocidEntitry to refMe's NSString's stringWithString:(strEntitry)
set ocidEntityNode to refMe's NSXMLDTDNode's alloc()'s initWithXMLString:(ocidEntitry)
ocidEntityNode's setDTDKind:(refMe's NSXMLAttributeEntityKind)
ocidDTD's addChild:(ocidEntityNode)
#Entitry付与
set strEntitry to ("<!ENTITY ns_extend \"http://ns.adobe.com/Extensibility/1.0/\">") as text
set ocidEntitry to refMe's NSString's stringWithString:(strEntitry)
set ocidEntityNode to refMe's NSXMLDTDNode's alloc()'s initWithXMLString:(ocidEntitry)
ocidEntityNode's setDTDKind:(refMe's NSXMLAttributeEntityKind)
ocidDTD's addChild:(ocidEntityNode)
##DTDをXMLDOCにセット
ocidXMLDoc's setDTD:(ocidDTD)
###ROOTエレメント
set ocidRootElement to refMe's NSXMLElement's elementWithName:("svg")
#【1】variableSets
set ocidVsetsElement to refMe's NSXMLElement's elementWithName:("variableSets")
set ocidSetNameSpace to refMe's NSXMLNode's namespaceWithName:("") stringValue:("&ns_vars;")
ocidVsetsElement's addNamespace:(ocidSetNameSpace)

#【2】variableSet
set ocidVsetElement to refMe's NSXMLElement's elementWithName:("variableSet")
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("varSetName") stringValue:("binding1"))
(ocidVsetElement's addAttribute:(ocidAddNode))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("locked") stringValue:("none"))
(ocidVsetElement's addAttribute:(ocidAddNode))

#【3−1】variables
set ocidVariablesElement to refMe's NSXMLElement's elementWithName:("variables")
################
#【3−2】variable
(*
可変テキスト:trait="textcontent" category="&ns_flows;"
フィアルパス:trait="fileref" category="&ns_vars;"
表示有無:trait="visibility" category="&ns_vars;"
表示有無?:trait="graphdata" category="&ns_graphs;"
*)
###########################
##ページレイアウト
###########################
repeat with itemEntries from 1 to numPageEntries by 1
  #【3−2−1】連番用の追加項目
  set ocidVariableElement to (refMe's NSXMLElement's elementWithName:("variable"))
  
  #【3−2−2】読み込みデータの項目
  repeat with itemFirstRowArray in ocidFirstRowArray
    set strFirstRowArray to itemFirstRowArray as text
    set ocidVariableElement to (refMe's NSXMLElement's elementWithName:("variable"))
    #ページのエントリー数を入れる
    set strSetVarName to ("E" & itemEntries & "-" & strFirstRowArray) as text
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("varName") stringValue:(strSetVarName))
(ocidVariableElement's addAttribute:(ocidAddNode))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("category") stringValue:("&ns_flows;"))
(ocidVariableElement's addAttribute:(ocidAddNode))
    set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("trait") stringValue:("textcontent"))
(ocidVariableElement's addAttribute:(ocidAddNode))
    #【3−2−2】variableを【3−1】variablesにセット
(ocidVariablesElement's addChild:(ocidVariableElement))
  end repeat
end repeat

################
#【4−1】DataSets
set ocidDataSetsElement to refMe's NSXMLElement's elementWithName:("v:sampleDataSets")
set ocidSetNameSpace to refMe's NSXMLNode's namespaceWithName:("v") stringValue:("&ns_vars;")
ocidDataSetsElement's addNamespace:(ocidSetNameSpace)
set ocidSetNameSpace to refMe's NSXMLNode's namespaceWithName:("") stringValue:("&ns_custom;")
ocidDataSetsElement's addNamespace:(ocidSetNameSpace)

################
#【4−2】DataSet
#データのリスト行数 先頭行の項目名行を除くので1引く
set numCntEditArray to ((count of ocidEditLineArray) - 1) as integer
#データの行数から何ページ分のデータ=dataSetの数
set numMakePage to (round of (numCntEditArray / numPageEntries) rounding up) as integer
#取り出すデータ行番号初期化
set numCntRowNoAll to 1 as integer
#作成される予定ページ数=dataSetの数ぶん繰り返す
repeat with itemdataSet from 1 to numMakePage by 1
  #【4−2】DataSetのエレメント
  set ocidDataSetElement to (refMe's NSXMLElement's elementWithName:("v:sampleDataSet"))
  #DataSetのアトリビュートに項目番号+2列目のデータで命名する
  set strSetDataSetName to (itemdataSet & ":ページ目") as text
  #↑の内容でdataSetNameをセット
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("dataSetName") stringValue:(strSetDataSetName))
(ocidDataSetElement's addAttribute:(ocidAddNode))
  #1ページに入る行目数分くりかえし
  repeat with itemPageEntries from 1 to numPageEntries by 1
    #指定行数の行データを取得
    set ocidRowStrings to (ocidEditLineArray's objectAtIndex:(numCntRowNoAll))
    #区切り文字タブでリストにして
    set ocidRowArray to (ocidRowStrings's componentsSeparatedByString:("\t"))
    #OS用の0スタートで行の項目数
    set numCntRowItemAll to ((count of ocidRowArray) - 1) as integer
    #行項目のリストから取得するための項目数初期化
    set numCntRowItem to 0 as integer
    #項目の数だけ繰り返し
    repeat with itemFirstRowArray in ocidFirstRowArray
      #ページ内での項目数+項目名でセット
      set strSetVarName to ("E" & itemPageEntries & "-" & itemFirstRowArray) as text
      set ocidDataSetChildElement to (refMe's NSXMLElement's elementWithName:(strSetVarName))
      #対象行列データを取得
      set strSetValieRowItem to (ocidRowArray's objectAtIndex:(numCntRowItem)) as text
      #Pエレメント内にテキストとして値をセット
      set ocidPElement to (refMe's NSXMLElement's elementWithName:("p"))
(ocidPElement's setStringValue:(strSetValieRowItem))
(ocidDataSetChildElement's addChild:(ocidPElement))
(ocidDataSetElement's addChild:(ocidDataSetChildElement))
      #カウントアップ
      set numCntRowItem to (numCntRowItem + 1) as integer
    end repeat
    set numCntRowNoAll to numCntRowNoAll + 1 as integer
    #データ行項目数より行カウンターが多くなったら終わり
    if numCntRowNoAll > (numCntEditArray) then
      exit repeat
    end if
  end repeat
  #【4−2】DataSetを【4−1】DataSetsにセット
(ocidDataSetsElement's addChild:(ocidDataSetElement))
end repeat

#【3−1】variablesを【2】のvariableSetにセット
ocidVsetElement's addChild:(ocidVariablesElement)
#【4−1】DataSetsを【2】のvariableSetにセット
ocidVsetElement's addChild:(ocidDataSetsElement)
#【2】variableSetを【1】のvariableSetsにセット
ocidVsetsElement's addChild:(ocidVsetElement)
#【1】のvariableSetsをROOTにセット
ocidRootElement's addChild:(ocidVsetsElement)
#
################################
###保存
ocidXMLDoc's setRootElement:(ocidRootElement)
###NSXMLNodePrettyPrint形式でデータにして
###NSXMLNodeCompactEmptyElementにすると少しデータサイズが節約できる
set ocidXMLdata to ocidXMLDoc's XMLDataWithOptions:(refMe's NSXMLNodeExpandEmptyElement)
###データをテキストに戻して
set ocidXMLString to refMe's NSString's alloc()'s initWithData:(ocidXMLdata) encoding:(refMe's NSUTF8StringEncoding)
###改行コードをWindowsに
set ocidSaveStrings to ocidXMLString's stringByReplacingOccurrencesOfString:(ocidLFChar) withString:(ocidCRLFChar)
###保存
set listDone to (ocidSaveStrings's writeToURL:(ocidSaveFilePathURL) atomically:true encoding:(refMe's NSUTF8StringEncoding) |error|:(reference))

return




|

TSV2AdobeXML タブ区切りテキストからAdobe Illustratorの変数印字用の『変数ライブラリ』を生成する

TSV2AdobeXML タブ区切りテキストからAdobe Illustratorの変数印字用の『変数ライブラリ』を生成する(1ページに複数面付け版)
https://quicktimer.cocolog-nifty.com/icefloe/2024/03/post-143f05.html
もあります
このページのスクリプトは1ページに1項目版です

変数パネルを使った可変テキスト
1:変数パネルを出す
2:変数パネル
3:ハンバーガーから『変数ライブラリの読み込み』
4:読み込んだ状態
5:テキストオブジェクトを生成して
6:使用したい変数を選択してから『テキスト動的に設定』を実行
7:動作確認

ダウンロード - makevariables.zip


1:変数パネルを出す
1_20240306130101
2:変数パネル
2_20240306130101
3:ハンバーガーから『変数ライブラリの読み込み』
3_20240306130101
4:読み込んだ状態
4_20240306130101
5:テキストオブジェクトを生成して
5_20240306130101
6:使用したい変数を選択してから『テキスト動的に設定』を実行
6_20240306130101
7:動作確認
7_20240306130101


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
(*
com.cocolog-nifty.quicktimer.icefloe
TSVタブ区切りテキストから
Adobe Illustrator用の変数用のXMLを生成します
【制限事項】その1
TSVの1行目の項目がデータセット名になります
表の1行目が項目名称になるようなTSVで利用してください
【制限事項】その2
可変テキストのみ設定可能です
他の要素の付与はご相談ください
*)
----+----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
set appFileManager to refMe's NSFileManager's defaultManager()


#################################
### 【1】入力ファイル
#################################
#ダイアログ
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.tab-separated-values-text"}
set strMes to ("ファイルを選んでください") as text
set strPrompt to ("ファイルを選んでください") as text
try
  ### ファイル選択時
  set aliasFilePath to (choose file strMes with prompt strPrompt default location aliasDesktopDirPath of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
if aliasFilePath is (missing value) then
return "選んでください"
end if
#ファイルパス
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)
#################################
### 【2】保存先
#################################
set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
set aliasContainerDirPath to (ocidContainerDirPathURL's absoluteURL()) as alias
set strMes to "フォルダを選んでください" as text
set strPrompt to "保存先フォルダを選択してください\n同名ファイルがある場合\n『上書き』になります" as text
try
  ###ダイアログを前面に出す
  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 aliasResponse to (choose folder strMes with prompt strPrompt default location aliasContainerDirPath with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
#戻り値エイリアスをURLに
set strSaveDirPath to (POSIX path of aliasResponse) as text
set ocidSaveDirPathStr to (refMe's NSString's stringWithString:(strSaveDirPath))
set ocidSaveDirPath to ocidSaveDirPathStr's stringByStandardizingPath()
set ocidSaveDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSaveDirPath) isDirectory:true)
##出力用ファイルパス
set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:("variables.xml")
#################################
### 【3】本処理
#################################
#ファイル読み込み
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
return "文字コードを判定出来ませんでした : " & strFileName
end if

#改行コードをUNIXに強制
set ocidCRChar to refMe's NSString's stringWithString:("\r")
set ocidLFChar to refMe's NSString's stringWithString:("\n")
set ocidCRLFChar to refMe's NSString's stringWithString:("\r\n")
set ocidReadStringsA to ocidReadString's stringByReplacingOccurrencesOfString:(ocidCRLFChar) withString:(ocidLFChar)
set ocidReadStrings to ocidReadStringsA's stringByReplacingOccurrencesOfString:(ocidCRChar) withString:(ocidLFChar)
#改行毎でリストにする
set ocidCharSet to (refMe's NSCharacterSet's newlineCharacterSet)
set ocidLineArray to (ocidReadStrings's componentsSeparatedByCharactersInSet:(ocidCharSet))
#出力用のリスト
set ocidEditLineArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
#読み取ったデータに項目連番を入れておく
set numCntLineNo to 0 as integer
repeat with itemLineArray in ocidLineArray
  set ocidEditLineText to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
  if numCntLineNo = 0 then
    set strAppendText to ("rowno\t") as text
(ocidEditLineText's appendString:(strAppendText))
(ocidEditLineText's appendString:(itemLineArray))
  else
    if (itemLineArray as text) is "" then
      exit repeat
    end if
    set strAppendText to (numCntLineNo & "\t") as text
(ocidEditLineText's appendString:(strAppendText))
(ocidEditLineText's appendString:(itemLineArray))
  end if
(ocidEditLineArray's addObject:(ocidEditLineText))
  #カウントアップ
  set numCntLineNo to (numCntLineNo + 1) as integer
end repeat

#最初の1行目だけ別で取得しておく
set ocidFirstObjectString to ocidEditLineArray's firstObject()
set ocidFirstRowArray to ocidFirstObjectString's componentsSeparatedByString:("\t")

################################
###XML初期化
set ocidXMLDoc to refMe's NSXMLDocument's alloc()'s init()
ocidXMLDoc's setVersion:("1.0")
ocidXMLDoc's setCharacterEncoding:("utf-8")
ocidXMLDoc's setDocumentContentKind:(refMe's NSXMLDocumentXMLKind)
###DTD生成
set ocidDTD to refMe's NSXMLDTD's alloc()'s init()
ocidDTD's setName:("svg")
ocidDTD's setPublicID:("-//W3C//DTD SVG 20001102//EN")
ocidDTD's setSystemID:("http://www.w3.org/TR/2000/CR-SVG-20001102/DTD/svg-20001102.dtd")
#Entitry付与
set strEntitry to ("<!ENTITY ns_graphs \"http://ns.adobe.com/Graphs/1.0/\">") as text
set ocidEntitry to refMe's NSString's stringWithString:(strEntitry)
set ocidEntityNode to refMe's NSXMLDTDNode's alloc()'s initWithXMLString:(ocidEntitry)
ocidEntityNode's setDTDKind:(refMe's NSXMLAttributeEntityKind)
ocidDTD's addChild:(ocidEntityNode)
#Entitry付与
set strEntitry to ("<!ENTITY ns_vars \"http://ns.adobe.com/Variables/1.0/\">") as text
set ocidEntitry to refMe's NSString's stringWithString:(strEntitry)
set ocidEntityNode to refMe's NSXMLDTDNode's alloc()'s initWithXMLString:(ocidEntitry)
ocidEntityNode's setDTDKind:(refMe's NSXMLAttributeEntityKind)
ocidDTD's addChild:(ocidEntityNode)
#Entitry付与
set strEntitry to ("<!ENTITY ns_imrep \"http://ns.adobe.com/ImageReplacement/1.0/\">") as text
set ocidEntitry to refMe's NSString's stringWithString:(strEntitry)
set ocidEntityNode to refMe's NSXMLDTDNode's alloc()'s initWithXMLString:(ocidEntitry)
ocidEntityNode's setDTDKind:(refMe's NSXMLAttributeEntityKind)
ocidDTD's addChild:(ocidEntityNode)
#Entitry付与
set strEntitry to ("<!ENTITY ns_custom \"http://ns.adobe.com/GenericCustomNamespace/1.0/\">") as text
set ocidEntitry to refMe's NSString's stringWithString:(strEntitry)
set ocidEntityNode to refMe's NSXMLDTDNode's alloc()'s initWithXMLString:(ocidEntitry)
ocidEntityNode's setDTDKind:(refMe's NSXMLAttributeEntityKind)
ocidDTD's addChild:(ocidEntityNode)
#Entitry付与
set strEntitry to ("<!ENTITY ns_flows \"http://ns.adobe.com/Flows/1.0/\">") as text
set ocidEntitry to refMe's NSString's stringWithString:(strEntitry)
set ocidEntityNode to refMe's NSXMLDTDNode's alloc()'s initWithXMLString:(ocidEntitry)
ocidEntityNode's setDTDKind:(refMe's NSXMLAttributeEntityKind)
ocidDTD's addChild:(ocidEntityNode)
#Entitry付与
set strEntitry to ("<!ENTITY ns_extend \"http://ns.adobe.com/Extensibility/1.0/\">") as text
set ocidEntitry to refMe's NSString's stringWithString:(strEntitry)
set ocidEntityNode to refMe's NSXMLDTDNode's alloc()'s initWithXMLString:(ocidEntitry)
ocidEntityNode's setDTDKind:(refMe's NSXMLAttributeEntityKind)
ocidDTD's addChild:(ocidEntityNode)
##DTDをXMLDOCにセット
ocidXMLDoc's setDTD:(ocidDTD)
###ROOTエレメント
set ocidRootElement to refMe's NSXMLElement's elementWithName:("svg")
#【1】variableSets
set ocidVsetsElement to refMe's NSXMLElement's elementWithName:("variableSets")
set ocidSetNameSpace to refMe's NSXMLNode's namespaceWithName:("") stringValue:("&ns_vars;")
ocidVsetsElement's addNamespace:(ocidSetNameSpace)

#【2】variableSet
set ocidVsetElement to refMe's NSXMLElement's elementWithName:("variableSet")
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("varSetName") stringValue:("binding1"))
(ocidVsetElement's addAttribute:(ocidAddNode))
set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("locked") stringValue:("none"))
(ocidVsetElement's addAttribute:(ocidAddNode))

#【3−1】variables
set ocidVariablesElement to refMe's NSXMLElement's elementWithName:("variables")
################
#【3−2】variable
(*
可変テキスト:trait="textcontent" category="&ns_flows;"
フィアルパス:trait="fileref" category="&ns_vars;"
表示有無:trait="visibility" category="&ns_vars;"
表示有無?:trait="graphdata" category="&ns_graphs;"
*)
#【3−2−1】連番用の追加項目
set ocidVariableElement to (refMe's NSXMLElement's elementWithName:("variable"))

#【3−2−2】読み込みデータの項目
repeat with itemFirstRowArray in ocidFirstRowArray
  set strFirstRowArray to itemFirstRowArray as text
  set ocidVariableElement to (refMe's NSXMLElement's elementWithName:("variable"))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("varName") stringValue:(strFirstRowArray))
(ocidVariableElement's addAttribute:(ocidAddNode))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("category") stringValue:("&ns_flows;"))
(ocidVariableElement's addAttribute:(ocidAddNode))
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("trait") stringValue:("textcontent"))
(ocidVariableElement's addAttribute:(ocidAddNode))
  #【3−2−2】variableを【3−1】variablesにセット
(ocidVariablesElement's addChild:(ocidVariableElement))
end repeat

################
#【4−1】DataSets
set ocidDataSetsElement to refMe's NSXMLElement's elementWithName:("v:sampleDataSets")
set ocidSetNameSpace to refMe's NSXMLNode's namespaceWithName:("v") stringValue:("&ns_vars;")
ocidDataSetsElement's addNamespace:(ocidSetNameSpace)
set ocidSetNameSpace to refMe's NSXMLNode's namespaceWithName:("") stringValue:("&ns_custom;")
ocidDataSetsElement's addNamespace:(ocidSetNameSpace)
################
#【4−2】DataSet
#データのリストの数
set numCntEditArray to (count of ocidEditLineArray) as integer
#データリストの2行目から最後まで繰り返す
repeat with itemIntNo from 1 to (numCntEditArray - 1) by 1
  #【4−2】DataSetのエレメント
  set ocidDataSetElement to (refMe's NSXMLElement's elementWithName:("v:sampleDataSet"))
  #DataSetのアトリビュートに項目番号+2列目のデータで命名する
  set ocidRowStrings to (ocidEditLineArray's objectAtIndex:(itemIntNo))
  set ocidRowArray to (ocidRowStrings's componentsSeparatedByString:("\t"))
  #ここが行番号
  set strRowNo to (ocidRowArray's objectAtIndex:(0)) as text
  #ここが2列目
  set strRowName to (ocidRowArray's objectAtIndex:(1)) as text
  #データセット名にする
  set strSetName to (strRowNo & ":" & strRowName) as text
  set ocidAddNode to (refMe's NSXMLNode's attributeWithName:("dataSetName") stringValue:(strSetName))
(ocidDataSetElement's addAttribute:(ocidAddNode))
  #【4−2】の子要素の生成
  set numCntFirstRowArray to (count of ocidFirstRowArray) as integer
  repeat with itemIntNo from 0 to (numCntFirstRowArray - 1) by 1
    set ocidFirstRowValue to (ocidFirstRowArray's objectAtIndex:(itemIntNo))
    set ocidDataSetChildElement to (refMe's NSXMLElement's elementWithName:(ocidFirstRowValue))
    #Pパラグラフのエレメントのテキストの値として生成する
    set strSetRowItem to (ocidRowArray's objectAtIndex:(itemIntNo))
    set ocidPElement to (refMe's NSXMLElement's elementWithName:("p"))
    #テキストの値を入れる
(ocidPElement's setStringValue:(strSetRowItem))
(ocidDataSetChildElement's addChild:(ocidPElement))
(ocidDataSetElement's addChild:(ocidDataSetChildElement))
  end repeat
(ocidDataSetsElement's addChild:(ocidDataSetElement))
end repeat

#【3−1】のvariablesを【2】のvariableSetにセット
ocidVsetElement's addChild:(ocidVariablesElement)
#【4−1】DataSetsを【2】のvariableSetにセット
ocidVsetElement's addChild:(ocidDataSetsElement)
#【2】variableSetを【1】のvariableSetsにセット
ocidVsetsElement's addChild:(ocidVsetElement)
#【1】のvariableSetsをROOTにセット
ocidRootElement's addChild:(ocidVsetsElement)
#
################################
###保存
ocidXMLDoc's setRootElement:(ocidRootElement)
###NSXMLNodePrettyPrint形式でデータにして
###NSXMLNodeCompactEmptyElementにすると少しデータサイズが節約できる
set ocidXMLdata to ocidXMLDoc's XMLDataWithOptions:(refMe's NSXMLNodeExpandEmptyElement)
###データをテキストに戻して
set ocidXMLString to refMe's NSString's alloc()'s initWithData:(ocidXMLdata) encoding:(refMe's NSUTF8StringEncoding)
###改行コードをWindowsに
set ocidSaveStrings to ocidXMLString's stringByReplacingOccurrencesOfString:(ocidLFChar) withString:(ocidCRLFChar)
###保存
set listDone to (ocidSaveStrings's writeToURL:(ocidSaveFilePathURL) atomically:true encoding:(refMe's NSUTF8StringEncoding) |error|:(reference))

return




|

TSV2QRバーコード(タブ区切りテキストからQRバーコードを生成する)

サンプルデータ入り

ダウンロード - maketsv2qr.zip


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
(*
com.cocolog-nifty.quicktimer.icefloe
TSVタブ区切りテキストからQRコードを生成します
*)
----+----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
##QRバーコードの最大幅
##(QRコード+クワイエットゾーンがあるのでひとまわり大きくなります)
property numMaxSize : 720 as integer

#################################
### 【1】入力ファイル
#################################
#ダイアログ
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.tab-separated-values-text"}
set strMes to ("ファイルを選んでください") as text
set strPrompt to ("ファイルを選んでください") as text
try
  ### ファイル選択時
  set aliasFilePath to (choose file strMes with prompt strPrompt default location aliasDesktopDirPath of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
if aliasFilePath is (missing value) then
return "選んでください"
end if
#パス
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)
#################################
### 【2】保存先
#################################
set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
set aliasContainerDirPath to (ocidContainerDirPathURL's absoluteURL()) as alias
set strMes to "フォルダを選んでください" as text
set strPrompt to "QRコードの保存先フォルダを選択してください\n同名ファイルがある場合\n『上書き』になります" as text
try
  ###ダイアログを前面に出す
  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 aliasResponse to (choose folder strMes with prompt strPrompt default location aliasContainerDirPath with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
#戻り値エイリアスをURLに
set strSaveDirPath to (POSIX path of aliasResponse) as text
set ocidSaveDirPathStr to (refMe's NSString's stringWithString:(strSaveDirPath))
set ocidSaveDirPath to ocidSaveDirPathStr's stringByStandardizingPath()
set ocidSaveDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSaveDirPath) isDirectory:true)
#################################
### 【3】本処理
#################################
#ファイル読み込み
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
  set strMes to ("文字コードを判定出来ませんでした : " & strFileName & "\n処理を中止します") as text
display alert strMes
return
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))
#################################
### 【4】ダイアログ
#################################
set ocidFirstLineString to ocidLineArray's firstObject()
set ocidFirstLineArray to (ocidFirstLineString's componentsSeparatedByString:("\t"))
set listFirstLineArray to ocidFirstLineArray as list
set strName to (name of current application) as text
if strName is "osascript" then
  tell application "Finder" to activate
  # tell application id "com.apple.appkit.xpc.openAndSavePanelService" to activate
else
  tell current application to activate
end if
###
set strTitle to ("選んでください") as text
set strPrompt to ("どの項目で作成しますか?") as text
try
  set listResponse to (choose from list listFirstLineArray with title strTitle with prompt strPrompt default items (item 1 of listFirstLineArray) 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 ocidIndex to ocidFirstLineArray's indexOfObject:(strResponse)
#Arrayの項目数
set numCntListLine to (count of ocidLineArray) as integer
#処理番号のカウント
set numCntRowNo to 1 as integer
#行毎処理
repeat with itemIntNo from 1 to (numCntListLine - 1) by 1
  set ocidLineData to (ocidLineArray's objectAtIndex:(itemIntNo))
  if (ocidLineData as text) is "" then
    exit repeat
  end if
  #行毎にタブ区切りでリスト化して
  set ocidRowLineArray to (ocidLineData's componentsSeparatedByString:("\t"))
  #選んだ項目をとりだす
  set ocidMakeString to (ocidRowLineArray's objectAtIndex:(ocidIndex))
  if strResponse contains "電話" then
    set strMakeString to ("tel:" & ocidMakeString) as text
  else if strResponse contains "メール" then
    set strMakeString to ("maileto:" & ocidMakeString) as text
  else
    set strMakeString to ocidMakeString as text
  end if
  #ファイル名に処理番号入れる場合
  set strFileName to (numCntRowNo & "-" & ocidMakeString) as text
  set ocidFileName to (refMe's NSString's stringWithString:(strFileName))
  #ファイル名に使えない文字を置換
  set ocidInvalidChar to (refMe's NSString's stringWithString:("[\\\\/:*?\"<>|]"))
  set ocidRegex to (refMe's NSRegularExpression's regularExpressionWithPattern:(ocidInvalidChar) options:(refMe's NSRegularExpressionCaseInsensitive) |error|:(reference))
  set ocidLength to refMe's NSMakeRange(0, (ocidFileName's |length|))
  set ocidSafeFileName to (ocidFileName's stringByReplacingOccurrencesOfString:(ocidInvalidChar) withString:("_") options:(refMe's NSRegularExpressionSearch) range:(ocidLength))
  #保存ファイル名とURLを定義しておく
  set ocidBaseSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(ocidSafeFileName))
  set ocidSaveFilePathURL to (ocidBaseSaveFilePathURL's URLByAppendingPathExtension:("png"))
  #QRコード生成を実行する
log doMakeQRcode(strMakeString, ocidSaveFilePathURL)
  set numCntRowNo to (numCntRowNo + 1) as integer
end repeat

set ocidSaveDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSaveDirPath) isDirectory:true)

#################################
### 【サブ】QRコード生成
#################################
to doMakeQRcode(argText, argSaveFilePathURL)
  #############################
  ### 【1】QRバーコード画像生成
  #############################
  #QRの内容になるテキスト
  set ocidInputString to refMe's NSString's stringWithString:(argText)
  #データに
  set ocidInputData to ocidInputString's dataUsingEncoding:(refMe's NSUTF8StringEncoding)
  ####CIQRCodeGenerator初期化
  set ocidQRcodeImage to refMe's CIFilter's filterWithName:("CIQRCodeGenerator")
ocidQRcodeImage's setDefaults()
  ###テキスト設定
ocidQRcodeImage's setValue:(ocidInputData) forKey:("inputMessage")
  ###読み取り誤差値設定L, M, Q, H
ocidQRcodeImage's setValue:("Q") forKey:("inputCorrectionLevel")
  ###QRコード本体のイメージ
  set ocidQRImage to ocidQRcodeImage's outputImage()
  ###QRコードの縦横取得 この数値が縦横のセル数
  set ocidQRDimension to ocidQRImage's extent()
  set listQRorigin to (item 1 of ocidQRDimension) as list
  set listQRsize to (item 2 of ocidQRDimension) as list
  set numQRsize to (item 1 of listQRsize) as integer
  ##############################
  
  ###整数で拡大しないとアレなので↑の値のニアなサイズになります
  ##この数値倍する
  set numScale to ((numMaxSize / numQRsize) div 1) as integer
  ####変換スケール作成-->拡大
  set recordScalse to refMe's CGAffineTransform's CGAffineTransformMakeScale(numScale, numScale)
  ##変換スケールを適応(元のサイズに元のサイズのスケール適応しても意味ないけど
  set ocidQRScaledImage to ocidQRImage's imageByApplyingTransform:(recordScalse)
  ###イメージデータを展開 拡大したQRコードのサイズ
  set ocidQRScaledRep to refMe's NSCIImageRep's imageRepWithCIImage:(ocidQRScaledImage)
  set ocidQRScaledSize to ocidQRScaledRep's |size|()
  set numQRScaledSize to (ocidQRScaledSize's width) as integer
  ##############################
  ###出力用のイメージの初期化
  set ocidNSImageScaled to refMe's NSImage's alloc()'s initWithSize:(ocidQRScaledSize)
  ###イメージデータを合成
ocidNSImageScaled's addRepresentation:(ocidQRScaledRep)
  ###出来上がったデータはOS_dispatch_data
  set ocidQRDispatchData to ocidNSImageScaled's TIFFRepresentation()
  ####NSBitmapImageRepに
  set ocidQRScaledBmpRep to refMe's NSBitmapImageRep's imageRepWithData:(ocidQRDispatchData)
  ###quiet zone用に画像をパディングする
  set numPadSize to (numQRScaledSize + (numScale * 6)) as integer
  ###左右に3セル分づつ余白 quiet zoneを足す
  ####まずは元のQRコードのサイズに3x2セルサイズ分足したサイズの画像を作って
  #QRコード自体に1セルクワイエットゾーンがあるので合計4セル分のクワイエットゾーンになる
  set ocidBaseRep to (refMe's NSBitmapImageRep's alloc()'s initWithBitmapDataPlanes:(missing value) pixelsWide:(numPadSize) pixelsHigh:(numPadSize) bitsPerSample:8 samplesPerPixel:4 hasAlpha:true isPlanar:false colorSpaceName:(refMe's NSCalibratedRGBColorSpace) bitmapFormat:(refMe's NSAlphaFirstBitmapFormat) bytesPerRow:0 bitsPerPixel:32)
  ###初期化
refMe's NSGraphicsContext's saveGraphicsState()
  ###Context
  set ocidContext to (refMe's NSGraphicsContext's graphicsContextWithBitmapImageRep:(ocidBaseRep))
  ###ビットマップイメージ
(refMe's NSGraphicsContext's setCurrentContext:(ocidContext))
  ###塗り色を『白』に指定して
refMe's NSColor's whiteColor()'s |set|()
  ###画像にする
refMe's NSRectFill({origin:{x:0, y:0}, |size|:{width:numPadSize, height:numPadSize}})
  ###出来上がった画像にQRバーコードを左右3セル分ずらした位置にCompositeSourceOverする
  set numPxWidth to ocidQRScaledBmpRep's pixelsWide()
  set numPadPxSize to (numPadSize - numPxWidth) / 2 as integer
ocidQRScaledBmpRep's drawInRect:{origin:{x:(numPadPxSize), y:(numPadPxSize)}, |size|:{width:numPadSize, Hight:numPadSize}} fromRect:{origin:{x:0, y:0}, |size|:{width:numPadSize, height:numPadSize}} operation:(refMe's NSCompositeSourceOver) fraction:1.0 respectFlipped:true hints:(missing value)
  ####画像作成終了
refMe's NSGraphicsContext's restoreGraphicsState()
  ####PNG用のプロパティ
  #保存用オプション
  set ocidPropertyDict to (refMe's NSMutableDictionary's alloc()'s initWithCapacity:0)
(ocidPropertyDict's setObject:(refMe's NSNumber's numberWithBool:(false)) forKey:(refMe's NSImageInterlaced))
(ocidPropertyDict's setObject:(refMe's NSNumber's numberWithFloat:(1 / 2.2)) forKey:(refMe's NSImageGamma))
  set ocidImageType to (refMe's NSBitmapImageFileTypePNG)
  #インラインデータに変換して
  set ocidSaveImageData to (ocidBaseRep's representationUsingType:(ocidImageType) |properties|:(ocidPropertyDict))
  #保存
  set listDone to (ocidSaveImageData's writeToURL:(argSaveFilePathURL) options:0 |error|:(reference))
end doMakeQRcode

|

tsvタブ区切りテキストに行番号を入れる

20240305033912836x896

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

#!/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 scripting additions
property refMe : a reference to current application
property refNSNotFound : a reference to 9.22337203685477E+18 + 5807

#################################
## 設定
## 1行目に番号入れる場合はfalseを
## 1行目は項目名で 2行目からはtrue
#################################
set boolFirstLineIsTitle to true as boolean
#デフォルトの改行コード 改行の無いテキストの場合用の指定
set ocidNewLineChar to (refMe's NSString's stringWithString:("\n"))
#################################
### 【1】入力ファイル
#################################
#ダイアログ
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.tab-separated-values-text"}
set strMes to ("ファイルを選んでください") as text
set strPrompt to ("ファイルを選んでください") as text
try
  ### ファイル選択時
  set aliasFilePath to (choose file strMes with prompt strPrompt default location aliasDesktopDirPath of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
if aliasFilePath is (missing value) then
return "選んでください"
end if
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)
#################################
### 【2】保存先
#################################
set ocidFileName to ocidFilePathURL's lastPathComponent()
set ocidContainerDirPathURL to ocidFilePathURL's URLByDeletingLastPathComponent()
set aliasContainerDirPath to (ocidContainerDirPathURL's absoluteURL()) as alias
set strMes to "フォルダを選んでください" as text
set strPrompt to "フォルダを選択してください\n入力フォルダと同じフォルダを選択すると\n『上書き』になります" as text
try
  ###ダイアログを前面に出す
  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 aliasResponse to (choose folder strMes with prompt strPrompt default location aliasContainerDirPath with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
#戻り値エイリアスをURLに
set strSaveDirPath to (POSIX path of aliasResponse) as text
set ocidSaveDirPathStr to (refMe's NSString's stringWithString:(strSaveDirPath))
set ocidSaveDirPath to ocidSaveDirPathStr's stringByStandardizingPath()
set ocidSaveDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSaveDirPath) isDirectory:true)
set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(ocidFileName)
#上書きチェック
if aliasContainerDirPath = aliasResponse then
log "同じフォルダに保存しようとしています"
  set strMes to "上書きを指定しました。\nファイルは上書きになります\nいいですか?" as text
  try
    ###ダイアログを前面に出す
    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
    #
    tell application (POSIX path of (path to frontmost application))
      set refResponse to (display alert ("【注意】:" & strMes) buttons {"OK", "処理中止"} default button "OK" cancel button "処理中止" as informational giving up after 20)
end tell
  on error
log "エラーしました"
return "エラーしました"
    error number -128
  end try
  if true is equal to (gave up of refResponse) then
return "時間切れですやりなおしてください"
    error number -128
  end if
  if "処理中止" is equal to (button returned of refResponse) then
return "処理を中止しました"
  end if
end if
#################################
### 【3】本処理
#################################
#ファイル読み込み
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
  set strMes to ("文字コードを判定出来ませんでした : " & strFileName & "\n処理を中止します") as text
display alert strMes
return
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))
#出力用のリスト
set ocidEditLineArray to refMe's NSMutableArray's alloc()'s initWithCapacity:(0)
#読み取ったデータに項目連番を入れておく
set numCntLineNo to 0 as integer
repeat with itemLineArray in ocidLineArray
  set ocidEditLineText to (refMe's NSMutableString's alloc()'s initWithCapacity:(0))
  if numCntLineNo = 0 then
    if boolFirstLineIsTitle is true then
      set strAppendText to ("NO\t") as text
    else if boolFirstLineIsTitle is false then
      set numCntLineNo to (numCntLineNo + 1) as integer
      set strAppendText to (numCntLineNo & "\t") as text
    end if
(ocidEditLineText's appendString:(strAppendText))
(ocidEditLineText's appendString:(itemLineArray))
  else
    if (itemLineArray as text) is "" then
      exit repeat
    end if
    set strAppendText to (numCntLineNo & "\t") as text
(ocidEditLineText's appendString:(strAppendText))
(ocidEditLineText's appendString:(itemLineArray))
  end if
(ocidEditLineArray's addObject:(ocidEditLineText))
  #カウントアップ
  set numCntLineNo to (numCntLineNo + 1) as integer
end repeat
##テキストに戻して
set ocidSaveStrings to ocidEditLineArray's componentsJoinedByString:(ocidNewLineChar)
#最後に改行を入れて改行で終わるタイプにする
ocidSaveStrings's appendString:(ocidNewLineChar)
#################################
### 【4】保存
#################################
set listDone to (ocidSaveStrings's writeToURL:(ocidSaveFilePathURL) atomically:true encoding:(refMe's NSUTF8StringEncoding) |error|:(reference))



|

テキストファイルエンコード変換


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

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
(*
com.cocolog-nifty.quicktimer.icefloe
テキストファイル
TSVやCSV javascriptの文字コードをまとめて変換します
選択ファイルと同じフォルダを保存先に選ぶと上書きになります

*)
----+----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

##############################
#入力
##############################
#デフォルトロケーション ここではデスクトップ
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 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 listUTI to {"public.text"}
set strMes to ("ファイルを選んでください") as text
set strPrompt to ("テキストファイルを選んでください\nファイルを選んでください") as text
try
  set listFilePath to (choose file strMes with prompt strPrompt default location aliasDesktopDirPath of type listUTI with invisibles, showing package contents and multiple selections allowed) as list
on error
log "エラーしました"
return "エラーしました"
end try
if listFilePath is (missing value) then
return "選んでください"
end if
##############################
#エンコード選択
##############################
#ユーザー選択用のレコード
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)} 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 valueForKey:(strResponse))

##############################
#保存先
##############################
#保存先用にユーザーが選択したファイルの最初のエイリアスを取得
set aliasFirstFilePath to (item 1 of listFilePath) as alias
#パスにして
set strFirstFilePath to (POSIX path of aliasFirstFilePath) as text
set ocidFirstFilePathStr to (refMe's NSString's stringWithString:(strFirstFilePath))
set ocidFirstFilePath to ocidFirstFilePathStr's stringByStandardizingPath()
set ocidFirstFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFirstFilePath) isDirectory:false)
#ファイルの親階層ディレクトリを取得して
set ocidContainerDirPathURL to ocidFirstFilePathURL's URLByDeletingLastPathComponent()
#エイリアスとしてダイアログに渡す
set aliasContainerDirPath to (ocidContainerDirPathURL's absoluteURL()) as alias
############
set strMes to "フォルダを選んでください" as text
set strPrompt to "フォルダを選択してください\n入力フォルダと同じフォルダを選択すると\n『上書き』になります" as text
try
  ###ダイアログを前面に出す
  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 aliasResponse to (choose folder strMes with prompt strPrompt default location aliasContainerDirPath with invisibles and showing package contents without multiple selections allowed) as alias
on error
log "エラーしました"
return "エラーしました"
end try
#戻り値エイリアスをURLに
set strSaveDirPath to (POSIX path of aliasResponse) as text
set ocidSaveDirPathStr to (refMe's NSString's stringWithString:(strSaveDirPath))
set ocidSaveDirPath to ocidSaveDirPathStr's stringByStandardizingPath()
set ocidSaveDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSaveDirPath) isDirectory:true)
#上書きチェック
if aliasContainerDirPath = aliasResponse then
log "同じフォルダに保存しようとしています"
  set strMes to "上書きを指定しました。\nファイルは上書きになります\nいいですか?" as text
  try
    ###ダイアログを前面に出す
    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
    #
    tell application (POSIX path of (path to frontmost application))
      set refResponse to (display alert ("【注意】:" & strMes) buttons {"OK", "処理中止"} default button "OK" cancel button "処理中止" as informational giving up after 20)
end tell
  on error
log "エラーしました"
return "エラーしました"
    error number -128
  end try
  if true is equal to (gave up of refResponse) then
return "時間切れですやりなおしてください"
    error number -128
  end if
  if "処理中止" is equal to (button returned of refResponse) then
return "処理を中止しました"
  end if
end if

##最初のファイル選択で選んだファイルの数だけ繰り返し
repeat with itemAliasFilePath in listFilePath
  #入力ファイルパス
  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 ocidFileName to ocidFilePathURL's lastPathComponent()
  set strFileName to ocidFileName as text
  ###ファイルのテキストを読み込み
  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
return "文字コードを判定出来ませんでした : " & strFileName
  end if
  #出力先 保存先パス 選んだフォルダ+ファイル名
  set ocidSaveFilePathURL to (ocidSaveDirPathURL's URLByAppendingPathComponent:(ocidFileName))
  #保存
  set listDone to (ocidReadString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(ocidSetEnc) |error|:(reference))
  if (item 1 of listDone) is true then
log "保存成功: " & strFileName
  else
log "エラーが発生しました: " & strFileName
  end if
end repeat






|

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

|

その他のカテゴリー

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