从swift中的文本文件中读取并处理空格

时间:2018-02-25 22:14:14

标签: arrays swift file-io

我正在学习Swift,我只想知道阅读文本文件的最佳方法,将其分解为行,然后在每行上取每个单词并将单词转换成可以是加载到类初始化程序中。

例如,如果我有这个文本文件:

**This is just a random text file, and the text on this line
and this line is not needed**
birth year    birth month   birth day     favourite colour
1990          11            12            red
1995           2             4            pink 
1992           5             3            orange
1987           3            19            blue

我想从每一行中获取出生年份,出生月份,出生日期和喜欢的颜色,然后将其加载到这样的类中:

Person(birthYear: 1990, birthMonth: 11, birthDay: 12, favouriteColour: red)

我想要读入的文本文件可能有不均匀的空格,因此输出将如下所示(对于给定的文本文件):

["**This", "is", "just", "a", "random", "text", "file,", "and", "the", "text", "on", "this", "line"]
["and", "this", "line", "is", "not", "needed**"]
["birth", "year", "", "", "", "birth", "month", "", "", "birth", "day", "", "", "", "", "favourite", "colour"]
["1990", "", "", "", "", "", "", "", "", "", "11", "", "", "", "", "", "", "", "", "", "", "", "12", "", "", "", "", "", "", "", "", "", "", "", "red"]
["1995", "", "", "", "", "", "", "", "", "", "", "2", "", "", "", "", "", "", "", "", "", "", "", "", "4", "", "", "", "", "", "", "", "", "", "", "", "pink", ""]
["1992", "", "", "", "", "", "", "", "", "", "", "5", "", "", "", "", "", "", "", "", "", "", "", "", "3", "", "", "", "", "", "", "", "", "", "", "", "orange"]
["1987", "", "", "", "", "", "", "", "", "", "", "3", "", "", "", "", "", "", "", "", "", "", "", "19", "", "", "", "", "", "", "", "", "", "", "", "blue"]

到目前为止,这是我的代码:

let path = "path to my file"

    if let contents = try? String(contentsOfFile: path) {

        // breaking the text file up into lines
        let lines = contents.components(separatedBy: "\n")

        // breaking the lines up into wordsw
        for line in lines {
            let elements = line.components(separatedBy: " ")
            print(elements)
        }

    }

我只是想知道在这些情况下处理空白区域的最佳方法是什么。提前感谢您的回复。

1 个答案:

答案 0 :(得分:2)

您可以使用简单的解决方案清除所有Tabs和Double空格。尝试使用这段代码。

func cleanTabsAndSpace(in text:String) -> String {
    var newText = text
    newText = newText.filter{ $0 != "\t" }.reduce(""){ str, char in
        if let lastChar = str.last, lastChar == " " && lastChar == char {
            return str
        }
        return str + String(char)
    }

    return newText.trimmingCharacters(in: .whitespacesAndNewlines)
}

创建此功能后,您可以在功能

中调用它
if let contents = try? String(contentsOfFile: path) {

    // Clean undesired chars
    let cleanContent = cleanTabsAndSpace(in: contents)

    // breaking the text file up into lines
    let lines = cleanContent.components(separatedBy: "\n")

    // breaking the lines up into wordsw
    for line in lines {
        let elements = line.components(separatedBy: " ")
        print(elements)
    }

}

通过此功能,您可以根据需要分离所有内容。现在您只需按照自己的意愿进行操作,根据需要解析内容并创建对象。

我只是考虑你在问题中描述的这种结构。

祝你好运朋友,如果你需要更多东西,请随时与我联系。