在Swift中从大型文本文件中读取行,直到遇到空行:用Swift的方式

7

我有以下文本文件结构(该文本文件相当大,约有10万行):

A|a1|111|111|111
B|111|111|111|111

A|a2|222|222|222
B|222|222|222|222
B|222|222|222|222

A|a3|333|333|333
B|333|333|333|333

...

我需要提取与给定关键字相关的文本。例如,如果我的关键字是A|a2,我需要将以下内容保存为字符串:
A|a2|222|222|222
B|222|222|222|222
B|222|222|222|222

在我的C++和Objective C项目中,我使用了以下方式的C++ getline函数:

std::ifstream ifs(dataPathStr.c_str());

NSString* searchKey = @"A|a2";
std::string search_string ([searchKey cStringUsingEncoding:NSUTF8StringEncoding]);

// read and discard lines from the stream till we get to a line starting with the search_string
std::string line;

while( getline( ifs, line ) && line.find(search_string) != 0 );

// check if we have found such a line, if not report an error
if( line.find(search_string) != 0 )
{
 data = DATA_DEFAULT ;
}

else{

   // we need to form a string that would include the whole set of data based on the selection
   dataStr = line + '\n' ; // result initially contains the first line

   // now keep reading line by line till we get an empty line or eof
   while(getline( ifs, line ) && !line.empty() )
   {
      dataStr += line + '\n'; // append this line to the result
   }

   data = [NSString stringWithUTF8String:navDataStr.c_str()];
} 

由于我正在使用Swift进行项目开发,我试图摆脱getline并使用一些"Cocoaish"的东西来替换它。但是我找不到一个好的Swift解决方案来解决上述问题。如果您有想法,我会非常感激。谢谢!


有趣的链接,谢谢。但是它并没有按照给定的方式工作:返回整个数据库,并且没有在/n或/n/r处停止。最好的。 - Igor Tupitsyn
我已经再次测试过了:每个nextLine()调用将作为字符串返回文件中的一行。默认分隔符是换行符(\n)。分隔符不包含在返回的字符串中。 - Martin R
非常感谢,马丁。我今天稍后会再次检查它。最好的祝福。 - Igor Tupitsyn
抱歉。我已添加了您的StreamReader.swift文件,并在UIViewController中实现了以下内容:let bundle = NSBundle.mainBundle() let pathNav = bundle.pathForResource("data_apt", ofType: "txt") if let aStreamReader = StreamReader(path: pathNav!) { while let line = aStreamReader.nextLine() { println(line) } 仍然读取整个数据库,而不是按分隔符\n读取行。 - Igor Tupitsyn
我已经测试过了,对我来说它可以工作。代码作为答案添加了。 - Martin R
1个回答

10

使用来自在Swift中逐行读取文件或URL的StreamReader类,您可以像这样在Swift中完成它:

let searchKey = "A|a2"

let bundle = NSBundle.mainBundle()
let pathNav = bundle.pathForResource("data_apt", ofType: "txt")
if let aStreamReader = StreamReader(path: pathNav!) {
    var dataStr = ""
    while let line = aStreamReader.nextLine() {
        if line.rangeOfString(searchKey, options: nil, range: nil, locale: nil) != nil {
            dataStr = line + "\n"
            break
        }
    }
    if dataStr == "" {
        dataStr = "DATA_DEFAULT"
    } else {
        while let line = aStreamReader.nextLine() {
            if countElements(line) == 0 {
                break
            }
            dataStr += line + "\n"
        }
    }
    aStreamReader.close()
    println(dataStr)
} else {
    println("cannot open file")
}

2
马丁。这太棒了。非常感谢!我实际上已经找到了问题所在。数据集文本文件是在Windows中创建的,存在换行符问题。我使用TextWrangler在Mac上重新创建了它,并使用Unix(LF)换行符,然后就好了!除了将您的姓名作为代码版权之外,还有任何商业项目中使用您的代码的条件吗?非常感谢! - Igor Tupitsyn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接