[OSX][iOS]データ解析 | Cocoa練習帳

[OSX][iOS]データ解析

データ・ファイルを解析する際の、よくあるパターンとして行単位で読み込んで、それを解析するというのがある。これをPerlで処理する場合、こんな感じになる。




#!/usr/bin/perl
my $line;
while ($line = <>) {


}



これをCocoaで行うとどうなるか?まずは、標準入力の内容を標準出力に印字する。




#import <Foundation/Foundation.h>
 
int main(int argc, const char * argv[])
{
    @autoreleasepool {        
        NSFileHandle    *fhi = [NSFileHandle fileHandleWithStandardInput];
        NSFileHandle    *fho = [NSFileHandle fileHandleWithStandardOutput];
 
        NSData  *datainput = [fhi readDataToEndOfFile];
        NSString    *str = [[NSString alloc] initWithData:datainput encoding:NSUTF8StringEncoding];
        
        NSData  *dataout = [[NSData alloc] initWithBytes:[str UTF8String] length:[str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
        [fho writeData:dataout];
    }
    return 0;
}



次に行単位で取り込む。




#import <Foundation/Foundation.h>


int main(int argc, const char * argv[])
{
    @autoreleasepool {        
        NSFileHandle    *fhi = [NSFileHandle fileHandleWithStandardInput];
        NSFileHandle    *fho = [NSFileHandle fileHandleWithStandardOutput];
 
        NSData  *datainput = [fhi readDataToEndOfFile];
        NSString    *str = [[NSString alloc] initWithData:datainput encoding:NSUTF8StringEncoding];
        
        NSError *error = NULL;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(.+)\n|(.+)"
                                                                               options:NSRegularExpressionCaseInsensitive
                                                                                 error:&error];
        NSArray    *array = [regex matchesInString:str options:0 range:NSMakeRange(0, str.length)];
        NSTextCheckingResult    *matches;
        for (matches in array) {
            NSString    *s = [str substringWithRange:[matches rangeAtIndex:0]];
            NSData  *dataout = [[NSData alloc] initWithBytes:[s UTF8String] length:[s lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
            [fho writeData:dataout];
        }
    }
    return 0;
}



ソースコード
GitHubからどうぞ。

https://github.com/murakami/workbook/tree/master/mac/analog - GitHub


関連情報
File System Programming Guide