トップ «前の日記(2012-06-27) 最新 次の日記(2012-06-29)» 編集

Cocoa練習帳

iOS/iPhone/iPad/watchOS/tvOS/MacOSX/Android プログラミング, Objective-C, Cocoa, Swiftなど

2012|01|02|03|04|05|06|07|08|09|10|11|12|
2013|01|02|03|04|05|06|07|08|09|10|11|12|
2014|01|02|03|04|05|06|07|08|09|10|11|12|
2015|01|02|03|04|05|06|07|08|09|10|11|12|
2016|01|02|03|04|05|06|07|08|09|10|11|12|
2017|01|02|03|04|05|06|07|08|09|10|11|12|
2018|01|02|03|04|05|06|07|08|09|10|11|12|
2019|01|02|03|04|05|06|07|08|09|10|11|12|
2020|01|02|03|04|05|06|07|08|09|10|11|12|
2021|01|02|03|04|05|06|07|08|09|10|11|12|
2022|01|02|03|04|05|06|07|08|09|10|11|12|
2023|01|02|03|04|05|06|07|08|09|10|11|12|
2024|01|02|03|

2012-06-28 [OSX][iOS]データ解析

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

#!/usr/bin/perl
my $line;
while ($line = <>) {
	chomp $line;
	print $line, "\n";
}

これを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

トップ «前の日記(2012-06-27) 最新 次の日記(2012-06-29)» 編集