NSScanner 和 CSV 文件

发布于 2024-10-24 20:40:58 字数 693 浏览 0 评论 0原文

我有一个包含四个字段的 CSV 文件:“Woonplaats”、“Gemeente”、“Provincie”、“Latitude”和“Longitude”。

示例值:

格拉夫兰,韦德梅伦,北荷兰省,52.24412000,5.12150000

使用下面的代码,我在文本中获取字符串,然后我想将其保存在数组中。我应该如何使用 NSScanner 从此字符串获取数据并将其保存在包含字典的数组中?

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"cities" ofType:@"csv"];
NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil ];
NSScanner *scanner = [NSScanner scannerWithString:myText];
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"\n ,"]];
NSMutableArray *newPoints = [NSMutableArray array];           

I have a CSV file with four fields, "Woonplaats", "Gemeente", "Provincie", "Latitude", and "Longitude".

Example values:

Graveland,Wijdemeren,Noord-Holland,52.24412000,5.12150000

Using the code below, I get the string in my text, and then I want to save it in array. How should I use NSScanner to get data from this string and save in an array containing dictionaries?

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"cities" ofType:@"csv"];
NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil ];
NSScanner *scanner = [NSScanner scannerWithString:myText];
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"\n ,"]];
NSMutableArray *newPoints = [NSMutableArray array];           

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怪我闹别瞎闹 2024-10-31 20:40:58

我相信这就是您正在寻找的。我使用 Dan Wood 论坛帖子和根据您的需要修改它。

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // insert code here...

    NSString *path =@"cities.csv";
    NSError *error;
    NSString *stringFromFileAtPath = [[NSString alloc]
                                      initWithContentsOfFile:path
                                      encoding:NSUTF8StringEncoding
                                      error:&error];

    NSMutableDictionary *lineDict = [NSMutableDictionary dictionary];
    NSArray  *lines  = [stringFromFileAtPath componentsSeparatedByString:@"\n"];
    NSEnumerator*theEnum = [lines objectEnumerator];
    NSArray  *keys  = nil;
    int  keyCount = 0;
    NSString *theLine;

    while (nil != (theLine = [theEnum nextObject]) )
    {
        if (![theLine isEqualToString:@""] && ![theLine hasPrefix:@"#"])    // ignore empty lines and lines that start with #
        {
            if (nil == keys) // Is keys not set yet? If so, process first real line as list of keys
            {
                keys = [theLine componentsSeparatedByString:@","];
                keyCount = [keys count];
            }
            else // A data line
            {
                NSArray    *values  = [theLine componentsSeparatedByString:@","];
                int valueCount = [values count];
                int i;

                for ( i = 0 ; i < keyCount && i < valueCount ; i++ )
                {
                    NSString *value = [values objectAtIndex:i];
                    if (nil != value && ![value isEqualToString:@""])
                    {
                        [lineDict setObject:value forKey:[keys objectAtIndex:i]];
                    }
                }
            }
        }
    }

    for (id key in lineDict)
    {
        NSLog(@"key: %@, value: %@", key, [lineDict objectForKey:key]);
    }

    [pool drain];
    return 0;
}

输出是:

2011-07-13 20:02:41.898 cities[5964:903] key: Latitude, value: 52.24412000
2011-07-13 20:02:41.900 cities[5964:903] key: Provincie, value: Noord-Holland
2011-07-13 20:02:41.900 cities[5964:903] key: Longitude, value: 5.12150000
2011-07-13 20:02:41.901 cities[5964:903] key: Gemeente, value: Wijdemeren
2011-07-13 20:02:41.902 cities[5964:903] key: Woonplaats, value: Graveland

I believe this is what you're looking for. I used Dan Wood forum post and modified it for your need.

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // insert code here...

    NSString *path =@"cities.csv";
    NSError *error;
    NSString *stringFromFileAtPath = [[NSString alloc]
                                      initWithContentsOfFile:path
                                      encoding:NSUTF8StringEncoding
                                      error:&error];

    NSMutableDictionary *lineDict = [NSMutableDictionary dictionary];
    NSArray  *lines  = [stringFromFileAtPath componentsSeparatedByString:@"\n"];
    NSEnumerator*theEnum = [lines objectEnumerator];
    NSArray  *keys  = nil;
    int  keyCount = 0;
    NSString *theLine;

    while (nil != (theLine = [theEnum nextObject]) )
    {
        if (![theLine isEqualToString:@""] && ![theLine hasPrefix:@"#"])    // ignore empty lines and lines that start with #
        {
            if (nil == keys) // Is keys not set yet? If so, process first real line as list of keys
            {
                keys = [theLine componentsSeparatedByString:@","];
                keyCount = [keys count];
            }
            else // A data line
            {
                NSArray    *values  = [theLine componentsSeparatedByString:@","];
                int valueCount = [values count];
                int i;

                for ( i = 0 ; i < keyCount && i < valueCount ; i++ )
                {
                    NSString *value = [values objectAtIndex:i];
                    if (nil != value && ![value isEqualToString:@""])
                    {
                        [lineDict setObject:value forKey:[keys objectAtIndex:i]];
                    }
                }
            }
        }
    }

    for (id key in lineDict)
    {
        NSLog(@"key: %@, value: %@", key, [lineDict objectForKey:key]);
    }

    [pool drain];
    return 0;
}

And the output is:

2011-07-13 20:02:41.898 cities[5964:903] key: Latitude, value: 52.24412000
2011-07-13 20:02:41.900 cities[5964:903] key: Provincie, value: Noord-Holland
2011-07-13 20:02:41.900 cities[5964:903] key: Longitude, value: 5.12150000
2011-07-13 20:02:41.901 cities[5964:903] key: Gemeente, value: Wijdemeren
2011-07-13 20:02:41.902 cities[5964:903] key: Woonplaats, value: Graveland
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文