郵便番号検索v3(ダウンロードURLが変わったのに対応・複数の検索語句の処理に挑戦してみた)
検索用のDBを作成
AppleScript サンプルコード
行番号 | ソース |
---|---|
001 | #!/usr/bin/env osascript |
002 | ----+----1----+----2----+-----3----+----4----+----5----+----6----+----7 |
003 | #com.cocolog-nifty.quicktimer.icefloe |
004 | #検索用のDBを作成します |
005 | #1回実行したら変更あるまで実行しなくてOK |
006 | ----+----1----+----2----+-----3----+----4----+----5----+----6----+----7 |
007 | use AppleScript version "2.8" |
008 | use framework "Foundation" |
009 | use framework "UniformTypeIdentifiers" |
010 | use framework "AppKit" |
011 | use scripting additions |
012 | property refMe : a reference to current application |
013 | set appFileManager to refMe's NSFileManager's defaultManager() |
014 | ########################## |
015 | #設定項目 |
016 | #ZIPファイルのURL |
017 | set strURL to ("https://www.post.japanpost.jp/zipcode/dl/utf/zip/utf_ken_all.zip") as text |
018 | |
019 | ########################## |
020 | #パス関連 |
021 | set ocidURLString to refMe's NSString's stringWithString:(strURL) |
022 | set ocidURL to refMe's NSURL's alloc()'s initWithString:(ocidURLString) |
023 | set strURL to ocidURL's absoluteString() as text |
024 | set ocidFileName to ocidURL's lastPathComponent() |
025 | #保存先 |
026 | set aliasPathToMe to (path to me) as alias |
027 | set strPathToMe to (POSIX path of aliasPathToMe) as text |
028 | set ocidPathToMeStr to refMe's NSString's stringWithString:(strPathToMe) |
029 | set ocidPathToMe to ocidPathToMeStr's stringByStandardizingPath() |
030 | set ocidPathToMeURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidPathToMe) isDirectory:(false) |
031 | set ocidContainerDirPathURL to ocidPathToMeURL's URLByDeletingLastPathComponent() |
032 | #保存先 |
033 | set ocidSaveDirPathURL to ocidContainerDirPathURL's URLByAppendingPathComponent:("data") isDirectory:(true) |
034 | #古いデータはゴミ箱へ |
035 | set listDone to (appFileManager's trashItemAtURL:(ocidSaveDirPathURL) resultingItemURL:(ocidSaveDirPathURL) |error| :(reference)) |
036 | #その上でフォルダを作っておく |
037 | set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0 |
038 | ocidAttrDict's setValue:(448) forKey:(refMe's NSFilePosixPermissions) |
039 | set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference) |
040 | # |
041 | set ocidDBFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:("postno.db") isDirectory:(false) |
042 | # |
043 | set ocidZipFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(ocidFileName) isDirectory:(false) |
044 | #コマンド用のパス |
045 | set strSaveDirPath to ocidSaveDirPathURL's |path|() as text |
046 | set strZipFilePath to ocidZipFilePathURL's |path|() as text |
047 | set strDBFilePath to ocidDBFilePathURL's |path|() as text |
048 | ########################## |
049 | #ダウンロード |
050 | set ocidOption to (refMe's NSDataReadingMappedIfSafe) |
051 | set listResponse to refMe's NSData's alloc()'s initWithContentsOfURL:(ocidURL) options:(ocidOption) |error| :(reference) |
052 | if (item 2 of listResponse) = (missing value) then |
053 | log "正常処理" |
054 | set ocidReadData to (item 1 of listResponse) |
055 | else if (item 2 of listResponse) ≠ (missing value) then |
056 | set strErrorNO to (item 2 of listResponse)'s code() as text |
057 | set strErrorMes to (item 2 of listResponse)'s localizedDescription() as text |
058 | refMe's NSLog("■:" & strErrorNO & strErrorMes) |
059 | return "エラーしました" & strErrorNO & strErrorMes |
060 | end if |
061 | ##NSDataで保存 |
062 | set ocidOption to (refMe's NSDataWritingAtomic) |
063 | set listDone to ocidReadData's writeToURL:(ocidZipFilePathURL) options:(ocidOption) |error| :(reference) |
064 | if (item 1 of listDone) is true then |
065 | log "writeToURL 正常処理" |
066 | else if (item 2 of listDone) ≠ (missing value) then |
067 | set strErrorNO to (item 2 of listDone)'s code() as text |
068 | set strErrorMes to (item 2 of listDone)'s localizedDescription() as text |
069 | refMe's NSLog("■:" & strErrorNO & strErrorMes) |
070 | return "writeToURL エラーしました" & strErrorNO & strErrorMes |
071 | end if |
072 | ########################## |
073 | #解凍 |
074 | set strCommandText to ("/usr/bin/bsdtar -xzvf \"" & strZipFilePath & "\" -C \"" & strSaveDirPath & "\"") |
075 | set strResponse to doZshShellScript(strCommandText) |
076 | if strResponse is false then |
077 | return "解凍に失敗しまし" |
078 | else |
079 | set listDone to (appFileManager's trashItemAtURL:(ocidZipFilePathURL) resultingItemURL:(ocidZipFilePathURL) |error| :(reference)) |
080 | end if |
081 | ########################## |
082 | #解凍後のファイル |
083 | set ocidOption to (refMe's NSDirectoryEnumerationSkipsHiddenFiles) |
084 | set ocidKeyArray to refMe's NSMutableArray's alloc()'s init() |
085 | ocidKeyArray's addObject:(refMe's NSURLPathKey) |
086 | set listResponse to (appFileManager's contentsOfDirectoryAtURL:(ocidSaveDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) |error| :(reference)) |
087 | #解凍したCSVファイル |
088 | set ocidCSVFilePathURL to (item 1 of listResponse)'s firstObject() |
089 | #DBにインポートするファイル |
090 | set ocidImportFilePathURL to ocidCSVFilePathURL's URLByAppendingPathExtension:("import.csv") |
091 | set strImportFilePath to ocidImportFilePathURL's |path|() as text |
092 | ########################## |
093 | #下準備 |
094 | set listResponse to refMe's NSString's alloc()'s initWithContentsOfURL:(ocidCSVFilePathURL) encoding:(refMe's NSUTF8StringEncoding) |error| :(reference) |
095 | set ocidReadString to (item 1 of listResponse) |
096 | #クオテーションを置換削除 |
097 | set ocidReadString to (ocidReadString's stringByReplacingOccurrencesOfString:("\"") withString:("")) |
098 | #保存 ファイルサイズが大きいので別名保存 |
099 | set listDone to ocidReadString's writeToURL:(ocidImportFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error| :(reference) |
100 | if (item 1 of listDone) is true then |
101 | log "writeToURL 正常終了" |
102 | else if (item 1 of listDone) is false then |
103 | log (item 2 of listDone)'s localizedDescription() as text |
104 | return "writeToURL 保存に失敗しました" |
105 | end if |
106 | ########################## |
107 | #【1】インポート |
108 | log "データインポート開始" |
109 | set strCommandText to ("/usr/bin/sqlite3 \"" & strDBFilePath & "\" <<EOF\nCREATE TABLE postalcode (code TEXT,old_no TEXT,p_no TEXT,prefecture_kana TEXT,city_kana TEXT,town_kana TEXT,prefecture TEXT,city TEXT,town TEXT,more INTEGER,azamore INTEGER,chomore INTEGER,containmore INTEGER,updatemore INTEGER,changemore INTEGER);\n.mode csv\n.import \"" & strImportFilePath & "\" postalcode\nEOF") |
110 | set strResponse to doZshShellScript(strCommandText) |
111 | if strResponse is false then |
112 | return "インポートに失敗しました" |
113 | else |
114 | log "データインポート終了" |
115 | end if |
116 | |
117 | ########################## |
118 | #【2】インポート |
119 | log "都道府県+地区町村作成開始" |
120 | set strCommandText to ("/usr/bin/sqlite3 \"" & strDBFilePath & "\" <<EOF\nALTER TABLE postalcode ADD COLUMN pref_and_city TEXT;\nEOF") |
121 | set strResponse to doZshShellScript(strCommandText) |
122 | if strResponse is false then |
123 | return "インポートに失敗しました" |
124 | else |
125 | log "都道府県+地区町村作成開始 OK" |
126 | end if |
127 | |
128 | ########################## |
129 | #【3】インポート |
130 | log "都道府県+地区町村 データ結合開始" |
131 | set strCommandText to ("/usr/bin/sqlite3 \"" & strDBFilePath & "\" <<EOF\nUPDATE postalcode SET pref_and_city = prefecture || city;\nEOF") |
132 | set strResponse to doZshShellScript(strCommandText) |
133 | if strResponse is false then |
134 | return "インポートに失敗しました" |
135 | else |
136 | log "都道府県+地区町村 データ結合 OK" |
137 | end if |
138 | |
139 | ########################## |
140 | #【4】インポート |
141 | log "地区町村+町名作成開始" |
142 | set strCommandText to ("/usr/bin/sqlite3 \"" & strDBFilePath & "\" <<EOF\nALTER TABLE postalcode ADD COLUMN city_and_town TEXT;\nEOF") |
143 | set strResponse to doZshShellScript(strCommandText) |
144 | if strResponse is false then |
145 | return "インポートに失敗しました" |
146 | else |
147 | log "地区町村+町名作成開始 OK" |
148 | end if |
149 | |
150 | ########################## |
151 | #【5】インポート |
152 | log "地区町村+町名作成開始 データ結合開始" |
153 | set strCommandText to ("/usr/bin/sqlite3 \"" & strDBFilePath & "\" <<EOF\nUPDATE postalcode SET city_and_town = city || town;\nEOF") |
154 | set strResponse to doZshShellScript(strCommandText) |
155 | if strResponse is false then |
156 | return "インポートに失敗しました" |
157 | else |
158 | log "地区町村+町名作成開始 データ結合開始 ok" |
159 | end if |
160 | |
161 | ########################## |
162 | #後処理 |
163 | set listDone to (appFileManager's trashItemAtURL:(ocidImportFilePathURL) resultingItemURL:(ocidImportFilePathURL) |error| :(reference)) |
164 | set listDone to (appFileManager's trashItemAtURL:(ocidCSVFilePathURL) resultingItemURL:(ocidCSVFilePathURL) |error| :(reference)) |
165 | |
166 | return "終了" |
167 | ########################## |
168 | # 【M】Bash 実行 |
169 | to doBashShellScript(argCommandText) |
170 | set strCommandText to argCommandText as text |
171 | log "\r" & strCommandText & "\r" |
172 | set strExec to ("/bin/bash -c '" & strCommandText & "'") as text |
173 | ########## |
174 | #コマンド実行 |
175 | try |
176 | log "コマンド開始" |
177 | set strResnponse to (do shell script strExec) as text |
178 | log "コマンド終了" |
179 | on error |
180 | return false |
181 | end try |
182 | return strResnponse |
183 | end doBashShellScript |
184 | |
185 | ########################## |
186 | # 【N】ZSH 実行 |
187 | to doZshShellScript(argCommandText) |
188 | set strCommandText to argCommandText as text |
189 | log "\r" & strCommandText & "\r" |
190 | set strExec to ("/bin/zsh -c '" & strCommandText & "'") as text |
191 | ########## |
192 | #コマンド実行 |
193 | try |
194 | log "コマンド開始" |
195 | set strResnponse to (do shell script strExec) as text |
196 | log "コマンド終了" |
197 | on error |
198 | return false |
199 | end try |
200 | return strResnponse |
201 | end doZshShellScript |
202 | return |
AppleScriptで生成しました |
検索用
AppleScript サンプルコード
行番号 | ソース |
---|---|
001 | #!/usr/bin/env osascript |
002 | ----+----1----+----2----+-----3----+----4----+----5----+----6----+----7 |
003 | # |
004 | # V2 都道府県市区町村を追加 |
005 | # V3ダウンロードURLとファイル名が変更されたのに対応 |
006 | # com.cocolog-nifty.quicktimer.icefloe |
007 | ----+----1----+----2----+-----3----+----4----+----5----+----6----+----7 |
008 | ##自分環境がos12なので2.8にしているだけです |
009 | use AppleScript version "2.8" |
010 | use framework "Foundation" |
011 | use framework "AppKit" |
012 | use scripting additions |
013 | |
014 | property refMe : a reference to current application |
015 | property refNSNotFound : a reference to 9.22337203685477E+18 + 5807 |
016 | |
017 | ############################# |
018 | ### クリップボードの中身取り出し |
019 | ###初期化 |
020 | set ocidPasteboard to refMe's NSPasteboard's generalPasteboard() |
021 | set ocidPastBoardTypeArray to ocidPasteboard's types |
022 | ###テキストがあれば |
023 | set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text" |
024 | if boolContain = true then |
025 | ###値を格納する |
026 | tell application "Finder" |
027 | set strReadString to (the clipboard as text) as text |
028 | end tell |
029 | ###Finderでエラーしたら |
030 | else |
031 | set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType" |
032 | if boolContain = true then |
033 | set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value) |
034 | set strReadString to ocidReadString as text |
035 | else |
036 | log "テキストなし" |
037 | set strReadString to "" as text |
038 | end if |
039 | end if |
040 | |
041 | ############################# |
042 | ###DBファイルへのパス |
043 | tell application "Finder" |
044 | set aliasPathToMe to (path to me) as alias |
045 | set aliasContainerDirPath to (container of aliasPathToMe) as alias |
046 | end tell |
047 | set strContainerDirPath to (POSIX path of aliasContainerDirPath) as text |
048 | set ocidContainerDirPathStr to refMe's NSString's stringWithString:(strContainerDirPath) |
049 | set ocidContainerDirPath to ocidContainerDirPathStr's stringByStandardizingPath() |
050 | set ocidContainerDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidContainerDirPath) isDirectory:true) |
051 | set ocidDBFilePathURL to ocidContainerDirPathURL's URLByAppendingPathComponent:("data/postno.db") |
052 | set strDbFilePathURL to (ocidDBFilePathURL's |path|()) as text |
053 | |
054 | set strMes to ("住所で検索 一部分でも可\r神奈川とかで指定すると検索結果が多くなります\n郵便番号で検索の場合は数字のみ(ハイフン除いてください)") as text |
055 | set strQueryText to strReadString as text |
056 | |
057 | ############################## |
058 | ###ダイアログ |
059 | set strName to (name of current application) as text |
060 | if strName is "osascript" then |
061 | tell application "Finder" to activate |
062 | else |
063 | tell current application to activate |
064 | end if |
065 | set aliasIconPath to POSIX file "/System/Applications/Calculator.app/Contents/Resources/AppIcon.icns" as alias |
066 | try |
067 | set recordResult to (display dialog strMes with title "郵便番号検索" default answer strQueryText buttons {"OK", "キャンセル"} default button "OK" with icon aliasIconPath giving up after 20 without hidden answer) as record |
068 | if "OK" is equal to (button returned of recordResult) then |
069 | set strReturnedText to (text returned of recordResult) as text |
070 | else if (gave up of recordResult) is true then |
071 | return "時間切れです" |
072 | else |
073 | return "キャンセル" |
074 | end if |
075 | on error |
076 | log "エラーしました" |
077 | return |
078 | end try |
079 | ############################## |
080 | ###戻り値整形 |
081 | set ocidResponseText to (refMe's NSString's stringWithString:(strReturnedText)) |
082 | ###タブと改行を除去しておく |
083 | set ocidTextM to refMe's NSMutableString's alloc()'s initWithCapacity:(0) |
084 | ocidTextM's appendString:(ocidResponseText) |
085 | ##改行除去 |
086 | set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\n") withString:("") |
087 | set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\r") withString:("") |
088 | ##タブ除去 |
089 | set ocidTextM to ocidTextM's stringByReplacingOccurrencesOfString:("\t") withString:("") |
090 | set strSearchText to ocidTextM as text |
091 | ############################## |
092 | ###ひらがなのみの場合はカタカナに |
093 | set listRegex to refMe's NSRegularExpression's regularExpressionWithPattern:("^[ぁ-んー]+$") options:(0) |error| :(reference) |
094 | set ocidRegex to (item 1 of listRegex) |
095 | set ocidTextRange to refMe's NSMakeRange(0, (ocidTextM's |length|())) |
096 | log ocidTextRange |
097 | set numMach to ocidRegex's numberOfMatchesInString:(ocidTextM) options:0 range:(ocidTextRange) |
098 | if (numMach as integer) = 1 then |
099 | set ocidTransform to (refMe's NSStringTransformHiraganaToKatakana) |
100 | set ocidTextM to (ocidTextM's stringByApplyingTransform:(ocidTransform) |reverse|:false) |
101 | end if |
102 | ###数字がなければ全角に |
103 | set ocidTransform to (refMe's NSStringTransformFullwidthToHalfwidth) |
104 | set ocidTextM to (ocidTextM's stringByApplyingTransform:(ocidTransform) |reverse|:true) |
105 | ############################## |
106 | #この時点でスペースは全角だから |
107 | set ocidKeyWordArray to ocidTextM's componentsSeparatedByString:(" ") |
108 | #判定用 |
109 | set appPredicateNum to refMe's NSPredicate's predicateWithFormat_("SELF MATCHES %@", "^[0-9]+$") |
110 | set appPredicateKana to refMe's NSPredicate's predicateWithFormat_("SELF MATCHES %@", "^[\\u30A0-\\u30FF]+$") |
111 | #県名リスト |
112 | set listPrefecture to {"北海道", "青森", "岩手", "宮城", "秋田", "山形", "福島", "茨城", "栃木", "群馬", "埼玉", "千葉", "東京", "神奈川", "新潟", "富山", "石川", "福井", "山梨", "長野", "岐阜", "静岡", "愛知", "三重", "滋賀", "京都", "大阪", "兵庫", "奈良", "和歌山", "鳥取", "島根", "岡山", "広島", "山口", "徳島", "香川", "愛媛", "高知", "福岡", "佐賀", "長崎", "熊本", "大分", "宮崎", "鹿児島", "沖縄"} as list |
113 | #県名リスト |
114 | set listPrefectureFull to {"北海道", "青森県", "岩手県", "宮城県", "秋田県", "山形県", "福島県", "茨城県", "栃木県", "群馬県", "埼玉県", "千葉県", "東京都", "神奈川県", "新潟県", "富山県", "石川県", "福井県", "山梨県", "長野県", "岐阜県", "静岡県", "愛知県", "三重県", "滋賀県", "京都府", "大阪府", "兵庫県", "奈良県", "和歌山県", "鳥取県", "島根県", "岡山県", "広島県", "山口県", "徳島県", "香川県", "愛媛県", "高知県", "福岡県", "佐賀県", "長崎県", "熊本県", "大分県", "宮崎県", "鹿児島県", "沖縄県"} as list |
115 | #県名リスト |
116 | set listPrefectureKANA to {"ホッカイドウ", "アオモリ", "イワテ", "ミヤギ", "アキタ", "ヤマガタ", "フクシマ", "イバラキ", "トチギ", "グンマ", "サイタマ", "チバ", "トウキョウ", "カナガワ", "ニイガタ", "トヤマ", "イシカワ", "フクイ", "ヤマナシ", "ナガノ", "ギフ", "シズオカ", "アイチ", "ミエ", "シガ", "キョウト", "オオサカ", "ヒョウゴ", "ナラ", "ワカヤマ", "トットリ", "シマネ", "オカヤマ", "ヒロシマ", "ヤマグチ", "トクシマ", "カガワ", "エヒメ", "コウチ", "フクオカ", "サガ", "ナガサキ", "クマモト", "オオイタ", "ミヤザキ", "カゴシマ", "オキナワ"} as list |
117 | #県名リスト |
118 | set listPrefectureKANAFull to {"ホッカイドウ", "アオモリケン", "イワテケン", "ミヤギケン", "アキタケン", "ヤマガタケン", "フクシマケン", "イバラキケン", "トチギケン", "グンマケン", "サイタマケン", "チバケン", "トウキョウト", "カナガワケン", "ニイガタケン", "トヤマケン", "イシカワケン", "フクイケン", "ヤマナシケン", "ナガノケン", "ギフケン", "シズオカケン", "アイチケン", "ミエケン", "シガケン", "キョウトフ", "オオサカフ", "ヒョウゴケン", "ナラケン", "ワカヤマケン", "トットリケン", "シマネケン", "オカヤマケン", "ヒロシマケン", "ヤマグチケン", "トクシマケン", "カガワケン", "エヒメケン", "コウチケン", "フクオカケン", "サガケン", "ナガサキケン", "クマモトケン", "オオイタケン", "ミヤザキケン", "カゴシマケン", "オキナワケン"} as list |
119 | #################### |
120 | #クエリー文を生成 |
121 | set boolContainPno to false as boolean |
122 | set boolContainPrefecture to false as boolean |
123 | #次工程に回す |
124 | set listSearchCom to {} as list |
125 | repeat with itemKeyWord in ocidKeyWordArray |
126 | #数字のみ判定 |
127 | set boolNUM to (appPredicateNum's evaluateWithObject:(itemKeyWord)) as boolean |
128 | #カタカナのみ判定 |
129 | set boolKANA to (appPredicateKana's evaluateWithObject:(itemKeyWord)) as boolean |
130 | #数字なら |
131 | if boolNUM is true then |
132 | #郵便番号検索 |
133 | set ocidTransform to (refMe's NSStringTransformFullwidthToHalfwidth) |
134 | set strItemKeyWord to (itemKeyWord's stringByApplyingTransform:(ocidTransform) |reverse|:false) as text |
135 | set strAddCom to ("p_no LIKE '%" & strItemKeyWord & "%'") as text |
136 | copy strAddCom to end of listSearchCom |
137 | set boolContainPno to true as boolean |
138 | else if boolKANA is true then |
139 | #カナなら |
140 | set ocidTransform to (refMe's NSStringTransformFullwidthToHalfwidth) |
141 | set strItemKeyWord to (itemKeyWord's stringByApplyingTransform:(ocidTransform) |reverse|:true) as text |
142 | if listPrefectureKANA contains strItemKeyWord then |
143 | #県名リストに含まれる検索語句の場合 |
144 | set strAddCom to ("prefecture_kana LIKE '%" & strItemKeyWord & "%'") as text |
145 | copy strAddCom to end of listSearchCom |
146 | set boolContainPrefecture to true as boolean |
147 | else if listPrefectureKANAFull contains strItemKeyWord then |
148 | #県名リストに含まれる検索語句の場合 |
149 | set strAddCom to ("prefecture_kana IS '" & strItemKeyWord & "'") as text |
150 | copy strAddCom to end of listSearchCom |
151 | set boolContainPrefecture to true as boolean |
152 | else |
153 | set strAddCom to ("city_kana LIKE '%" & strItemKeyWord & "%'") as text |
154 | copy strAddCom to end of listSearchCom |
155 | set strAddCom to ("town_kana LIKE '%" & strItemKeyWord & "%'") as text |
156 | copy strAddCom to end of listSearchCom |
157 | end if |
158 | else |
159 | #数字 カナ 以外なら |
160 | set strItemKeyWord to itemKeyWord as text |
161 | #県名リストに含まれる検索語句の場合 |
162 | if listPrefecture contains strItemKeyWord then |
163 | set strAddCom to ("prefecture LIKE '%" & strItemKeyWord & "%'") as text |
164 | copy strAddCom to beginning of listSearchCom |
165 | #set strAddCom to ("city_and_town LIKE '%" & strItemKeyWord & "%'") as text |
166 | # copy strAddCom to end of listSearchCom |
167 | set boolContainPrefecture to true as boolean |
168 | else if listPrefectureFull contains strItemKeyWord then |
169 | #県名リストに含まれる検索語句の場合 |
170 | set strAddCom to ("prefecture IS '" & strItemKeyWord & "'") as text |
171 | copy strAddCom to beginning of listSearchCom |
172 | set strAddCom to ("city_and_town LIKE '%" & strItemKeyWord & "%'") as text |
173 | copy strAddCom to end of listSearchCom |
174 | set boolContainPrefecture to true as boolean |
175 | else |
176 | set strAddCom to ("city_and_town LIKE '%" & strItemKeyWord & "%'") as text |
177 | copy strAddCom to end of listSearchCom |
178 | #set strAddCom to ("town LIKE '%" & strItemKeyWord & "%'") as text |
179 | #copy strAddCom to end of listSearchCom |
180 | end if |
181 | end if |
182 | end repeat |
183 | |
184 | ############################## |
185 | ##クエリーを生成 |
186 | #メインのクエリー |
187 | set strQuery to ("") as text |
188 | #AND検索用のサブクエリー |
189 | set strSubQuery to ("") as text |
190 | #検索語句数 |
191 | set numCntList to (count of listSearchCom) as integer |
192 | #検索語句の数だけ繰り返し |
193 | repeat with itemNo from 1 to numCntList by 1 |
194 | #検索語句 |
195 | set strItemCom to (item itemNo of listSearchCom) as text |
196 | #検索語句が1つだけなら |
197 | if numCntList = 1 then |
198 | set strSubQuery to ("" & strQuery & strItemCom & "") as text |
199 | exit repeat |
200 | end if |
201 | ##検索語句が複数ある場合 |
202 | #郵便番号をメインのクエリーに |
203 | if strItemCom contains "p_no" then |
204 | set strPnoQuery to strItemCom as text |
205 | end if |
206 | #県名をメインのクエリーに |
207 | if strItemCom contains "prefecture" then |
208 | set strPrefectureQuery to strItemCom as text |
209 | end if |
210 | ##検索語句が最初なら |
211 | if itemNo = 1 then |
212 | if strItemCom contains "p_no" then |
213 | #郵便番号はAND |
214 | set strSubQuery to (strItemCom & " AND " & "") as text |
215 | else if strItemCom contains "prefecture" then |
216 | #県名はAND |
217 | set strSubQuery to (strItemCom & " AND " & "") as text |
218 | else |
219 | #それ以外の場合 |
220 | #次の検索語句を調べて |
221 | set strItemNextCom to (item (itemNo + 1) of listSearchCom) as text |
222 | #次が郵便番号はAND |
223 | if strItemNextCom contains "p_no" then |
224 | set strSubQuery to ("" & strItemCom & " AND " & "") as text |
225 | else if strItemNextCom contains "prefecture" then |
226 | #次が県名はAND |
227 | set strSubQuery to ("" & strItemCom & " AND " & "") as text |
228 | else |
229 | #それ以外の場合はOR |
230 | set strSubQuery to (strItemCom & " OR " & "") as text |
231 | end if |
232 | end if |
233 | else if itemNo = numCntList then |
234 | set strSubQuery to ("" & strSubQuery & strItemCom & "") as text |
235 | else |
236 | if strItemCom contains "p_no" then |
237 | #郵便番号はAND |
238 | set strSubQuery to ("" & strSubQuery & strItemCom & " AND " & "") as text |
239 | else if strItemCom contains "prefecture" then |
240 | #県名はAND |
241 | set strSubQuery to ("" & strSubQuery & strItemCom & " AND " & "") as text |
242 | else |
243 | set strItemNextCom to (item (itemNo + 1) of listSearchCom) as text |
244 | if strItemNextCom contains "p_no" then |
245 | #郵便番号はAND |
246 | set strSubQuery to ("" & strSubQuery & strItemCom & " AND " & "") as text |
247 | else if strItemNextCom contains "prefecture" then |
248 | #県名はAND |
249 | set strSubQuery to ("" & strSubQuery & strItemCom & " AND " & "") as text |
250 | else |
251 | #それ以外の場合はOR |
252 | set strSubQuery to ("" & strSubQuery & strItemCom & " OR " & "") as text |
253 | end if |
254 | |
255 | end if |
256 | end if |
257 | |
258 | end repeat |
259 | #メインのクエリーにサブクエリーをANDでセット |
260 | #郵便番号を優先する |
261 | if boolContainPrefecture is true then |
262 | set strQuery to ("" & strPrefectureQuery & " AND (" & strSubQuery & ")") as text |
263 | else if boolContainPno is true then |
264 | set strQuery to ("" & strPnoQuery & " AND (" & strSubQuery & ")") as text |
265 | else |
266 | #メインのクエリーが無い場合はそのままセット |
267 | set strQuery to strSubQuery |
268 | end if |
269 | #コマンド整形 |
270 | set strCommandText to ("/usr/bin/sqlite3 \"" & strDbFilePathURL & "\" -tabs \"SELECT COUNT(*) FROM postalcode WHERE " & strQuery & ";\"") as text |
271 | log "\r" & strCommandText & "\r" |
272 | ###検索結果の件数 |
273 | set numQueryCnt to (do shell script strCommandText) as integer |
274 | |
275 | |
276 | ############################## |
277 | ###件数が100超える場合は中止を促す |
278 | if numQueryCnt > 100 then |
279 | log "検索結果100件超です" |
280 | ###ダイアログを前面に出す |
281 | set strName to (name of current application) as text |
282 | if strName is "osascript" then |
283 | tell application "Finder" to activate |
284 | else |
285 | tell current application to activate |
286 | end if |
287 | ##1件の処理時間 |
288 | set numMin to (0.01 * numQueryCnt) as integer |
289 | set strAlertMes to "検索結果100件超です(" & numQueryCnt & "件)\r継続すると結果表示まで約:" & numMin & "秒かかります" as text |
290 | try |
291 | set recordResponse to (display alert ("【選んでください】\r" & strAlertMes) buttons {"継続", "終了"} default button "継続" cancel button "終了" as informational giving up after 10) as record |
292 | on error |
293 | log "エラーしました" |
294 | return "キャンセルしました。処理を中止します。再度実行してください" |
295 | end try |
296 | if true is equal to (gave up of recordResponse) then |
297 | return "時間切れです。処理を中止します。再度実行してください" |
298 | end if |
299 | else if numQueryCnt = 0 then |
300 | log "検索結果0件です" |
301 | end if |
302 | ####処理継続の場合はそのまま進む |
303 | |
304 | set strCommandText to ("/usr/bin/sqlite3 \"" & strDbFilePathURL & "\" -tabs \"SELECT * FROM postalcode WHERE " & strQuery & ";\"") as text |
305 | log strCommandText |
306 | |
307 | set strResponse to (do shell script strCommandText) as text |
308 | |
309 | |
310 | ######################################## |
311 | ##コマンドの戻り値を改行でリストに |
312 | set AppleScript's text item delimiters to "\r" |
313 | set listResponse to every text item of strResponse |
314 | set AppleScript's text item delimiters to "" |
315 | |
316 | ######################################## |
317 | ##HTML 基本構造 |
318 | ###スタイル |
319 | set strStylle to "<style>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 th { overflow-x: hidden;} tbody td { word-wrap: break-all;overflow-wrap: anywhere;text-overflow: ellipsis;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 } }</style>" |
320 | ###ヘッダー部 |
321 | set strHead to "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>[検索語句]" & strSearchText & "</title>" & strStylle & "</head><body>" |
322 | ###ボディ |
323 | set strBody to "" |
324 | ###最後 |
325 | set strHtmlEndBody to "</body></html>" |
326 | ###HTML書き出し用のテキスト初期化 |
327 | set ocidHTMLString to refMe's NSMutableString's alloc()'s initWithCapacity:0 |
328 | #### |
329 | (ocidHTMLString's appendString:strHead) |
330 | ######### |
331 | ###テーブルの開始部 |
332 | set strHTML to ("<table><caption title=\"タイトル\">検索結果:" & strReturnedText & "<br>検索結果数: " & numQueryCnt & "</caption>") as text |
333 | set strHTML to (strHTML & "<thead title=\"項目名称\"><tr><th title=\"項目1\" scope=\"row\" > 連番 </th><th title=\"項目2\" scope=\"col\"> 郵便番号 </th><th title=\"項目3\" scope=\"col\"> 住所 </th><th title=\"項目4\" scope=\"col\"> 読み </th><th title=\"項目5\" scope=\"col\">団体コード</th><th title=\"項目6\" scope=\"col\">リンク</th></tr></thead><tbody title=\"検索結果一覧\" >") as text |
334 | (ocidHTMLString's appendString:(strHTML)) |
335 | set numLineNo to 1 as integer |
336 | repeat with itemLine in listResponse |
337 | ###各行タブ区切りなのでタブでリストにする |
338 | set AppleScript's text item delimiters to "\t" |
339 | set listLineText to every text item of itemLine |
340 | set AppleScript's text item delimiters to "" |
341 | ###必要な項目を取得 |
342 | set strCityCode to (item 1 of listLineText) as text |
343 | set strPostNo to (item 3 of listLineText) as text |
344 | set strAddText to ((item 7 of listLineText) & (item 8 of listLineText) & (item 9 of listLineText)) as text |
345 | set strKana to ((item 4 of listLineText) & (item 5 of listLineText) & (item 6 of listLineText)) as text |
346 | ###リンク生成 |
347 | set strLinkURL to ("https://www.post.japanpost.jp/cgi-zip/zipcode.php?zip=" & strPostNo & "") |
348 | set strMapURL to ("https://www.google.com/maps/search/郵便番号+" & strPostNo & "") |
349 | set strMapAppURL to ("http://maps.apple.com/?q=郵便番号+" & strPostNo & "") |
350 | set strLINK to "<a href=\"" & strLinkURL & "\" target=\"_blank\">郵政</a> | <a href=\"" & strMapURL & "\" target=\"_blank\">Google</a> | <a href=\"" & strMapAppURL & "\" target=\"_blank\">Map</a>" |
351 | ###HTMLにして |
352 | set strHTML to ("<tr><th title=\"項番1\" scope=\"row\">" & numLineNo & "</th><td title=\"項目2\" style=\"white-space: nowrap;\">" & strPostNo & "</td><td title=\"項目3\">" & strAddText & "</td><td title=\"項目4\"><small>" & strKana & "</small></td><td title=\"項目5\">" & strCityCode & "</td><td title=\"項目6\">" & strLINK & "</td></tr>") as text |
353 | (ocidHTMLString's appendString:(strHTML)) |
354 | set numLineNo to numLineNo + 1 as integer |
355 | end repeat |
356 | |
357 | set strHTML to ("</tbody><tfoot><tr><th colspan=\"6\" title=\"フッター表の終わり\" scope=\"row\">post.japanpost.jp</th></tr></tfoot></table>") as text |
358 | ####テーブルまでを追加 |
359 | (ocidHTMLString's appendString:(strHTML)) |
360 | ####終了部を追加 |
361 | (ocidHTMLString's appendString:(strHtmlEndBody)) |
362 | |
363 | ###ディレクトリ |
364 | set appFileManager to refMe's NSFileManager's defaultManager() |
365 | set ocidTempDirURL to appFileManager's temporaryDirectory() |
366 | set ocidUUID to refMe's NSUUID's alloc()'s init() |
367 | set ocidUUIDString to ocidUUID's UUIDString |
368 | set ocidSaveDirPathURL to ocidTempDirURL's URLByAppendingPathComponent:(ocidUUIDString) isDirectory:true |
369 | set ocidAttrDict to refMe's NSMutableDictionary's alloc()'s initWithCapacity:0 |
370 | # 777-->511 755-->493 700-->448 766-->502 |
371 | ocidAttrDict's setValue:(511) forKey:(refMe's NSFilePosixPermissions) |
372 | set listBoolMakeDir to appFileManager's createDirectoryAtURL:(ocidSaveDirPathURL) withIntermediateDirectories:true attributes:(ocidAttrDict) |error| :(reference) |
373 | ###パス |
374 | |
375 | set strFileName to (strSearchText & ".html") as text |
376 | set ocidSaveFilePathURL to ocidSaveDirPathURL's URLByAppendingPathComponent:(strFileName) isDirectory:false |
377 | ###ファイルに書き出し |
378 | set listDone to ocidHTMLString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error| :(reference) |
379 | ####テキストエディタで開く |
380 | set aliasFilePath to (ocidSaveFilePathURL's absoluteURL()) as alias |
381 | (* |
382 | tell application "TextEdit" |
383 | activate |
384 | open file aliasFilePath |
385 | end tell |
386 | *) |
387 | tell application "Safari" |
388 | activate |
389 | open file aliasFilePath |
390 | end tell |
391 | |
392 | |
393 | |
394 | |
AppleScriptで生成しました |
| 固定リンク