集計スクリプト
VBScriptの備忘録
次の要件を満たすプログラムを書きました。
- あるディレクトリ以下にあるファイル一覧を取得する。
- ファイルから文字列を一行ずつ取り出し、同一のものが何個出現しているか集計する
- 対になった情報(HashTable)を指定した内容に出力する。key, valueとカンマで区切り、改行する。
- 上記作業はWindowsユーザーが行い、かつ、特別な環境構築は必要としない。
で以下のスクリプト。
Option Explicit Const CurrentDir = "./" Const SearchDir = "_合計/" Const OutputDir = "_集計/" '//================================================================ '// メイン処理 '//================================================================ Dim objFiles, objFile Dim targetDir = CurrentDir & SearchDir Set objFiles = CreateObject("Scripting.FileSystemObject").GetFolder(targetDir ).Files Dim file For Each objFile In objFiles Dim fileName fileName = objFile.Name Dim HashTable Set HashTable = getHashTableFrom( SearchDir & fileName ) Dim result result = StoreInto( HashTable, OutputDir & fileName ) Next MsgBox "完了" '//---------------------------------------------------------------- '// StoreInto( HashTable, OutputDir & file ) '//---------------------------------------------------------------- '// hashTableをファイルに格納します。 '//---------------------------------------------------------------- Function StoreInto(HashTable, file) Const ForReading = 1 Const ForWriting = 2 Const ForAppending = 8 Dim objOutput Set objOutput = CreateObject("Scripting.FileSystemObject").OpenTextFile(file, ForWriting, True ) Dim okey, oval for each okey in hashTable.keys wscript.echo okey wscript.echo hashTable(okey) objOutput.WriteLine(okey & ", " & hashTable(okey) ) next objOutput.Close StoreInto = 1 End Function '//---------------------------------------------------------------- '// getHashTableFrom(file) '//---------------------------------------------------------------- '// 同一の文字列の行が何回出現したかを連想配列に変換し、返します。 '//---------------------------------------------------------------- Function getHashTableFrom(file) Const ForReading = 1 Const ForWriting = 2 Const ForAppending = 8 Dim objInput Set objInput = CreateObject("Scripting.FileSystemObject").OpenTextFile(file, ForReading ) Dim hashTable, return set hashTable = createobject("scripting.dictionary") Do Until objInput.AtEndOfStream Dim line line = objInput.ReadLine If hashTable.exists(line) THEN hashTable.item(line) = hashTable.item(line) + 1 Else hashTable.item(line) = 1 END IF Loop objInput.Close Set getHashTableFrom = hashTable End Function