ios 如何使用 Swift 将文本文件逐行加载到数组中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24040141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I load a text file line by line into an array with Swift?
提问by Sebastian Krogull
How do I load a text file line by line into an array
with swift
?
如何将文本文件逐行加载到array
with 中swift
?
回答by Cezar
Something along the lines of:
类似的东西:
func arrayFromContentsOfFileWithName(fileName: String) -> [String]? {
guard let path = NSBundle.mainBundle().pathForResource(fileName, ofType: "txt") else {
return nil
}
do {
let content = try String(contentsOfFile:path, encoding: NSUTF8StringEncoding)
return content.componentsSeparatedByString("\n")
} catch _ as NSError {
return nil
}
}
This approach assumes the file in question is located in your app bundle.
这种方法假设有问题的文件位于您的应用程序包中。
回答by dbn
Swift 3 version based on the accepted answer:
基于公认答案的 Swift 3 版本:
func arrayFromContentsOfFileWithName(fileName: String) -> [String]? {
guard let path = Bundle.main.path(forResource: fileName, ofType: "txt") else {
return nil
}
do {
let content = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
return content.components(separatedBy: "\n")
} catch {
return nil
}
}
回答by Imanou Petit
With Swift 5, according to your needs, you can choose one of the 3 following ways in order to solve your problem.
使用 Swift 5,您可以根据需要,选择以下 3 种方式之一来解决您的问题。
#1. Using StringProtocol
's components(separatedBy:)
method
#1. usingStringProtocol
的components(separatedBy:)
方法
Foundation
provides String
a method called components(separatedBy:)
with the following declaration:
Foundation
提供String
了一个components(separatedBy:)
使用以下声明调用的方法:
func components(separatedBy separator: CharacterSet) -> [String]
Returns an array containing substrings from the string that have been divided by characters in the given set.
返回一个数组,其中包含字符串中已被给定集合中的字符划分的子字符串。
The code sample below shows how to use components(separatedBy:)
with its parameter set to CharacterSet.newlines
in order to load the content of a text file line by line into an array:
下面的代码示例显示了如何使用components(separatedBy:)
其参数设置为CharacterSet.newlines
将文本文件的内容逐行加载到数组中:
import Foundation
let path = Bundle.main.path(forResource: "Lorem Ipsum", ofType: "txt")!
let text = try! String(contentsOfFile: path, encoding: String.Encoding.utf8)
let lines = text.components(separatedBy: CharacterSet.newlines)
print(lines)
As an alternative, you can use the overloading of components(separatedBy:)
that takes a parameter of type String
. The code sample below shows how to use it:
作为替代方案,您可以使用带类型参数的的重载components(separatedBy:)
String
。下面的代码示例展示了如何使用它:
import Foundation
let path = Bundle.main.path(forResource: "Lorem Ipsum", ofType: "txt")!
let text = try! String(contentsOfFile: path, encoding: String.Encoding.utf8)
let lines = text.components(separatedBy: "\n")
print(lines)
?? You should however prefer the overloading of components(separatedBy:)
that takes a CharacterSet
parameter and use it with the value CharacterSet.newlines
as this will manage all new line characters (U+000A ~ U+000D, U+0085, U+2028, and U+2029).
?? 但是,您应该更喜欢重载components(separatedBy:)
带CharacterSet
参数并将其与值一起使用,CharacterSet.newlines
因为这将管理所有换行符(U+000A ~ U+000D、U+0085、U+2028 和 U+2029)。
#2. Using StringProtocol
's enumerateSubstrings(in:options:_:)
method
#2. usingStringProtocol
的enumerateSubstrings(in:options:_:)
方法
Foundation
provides String
a method called enumerateSubstrings(in:options:_:)
. The code sample below shows how to use enumerateSubstrings(in:options:_:)
with options
parameter value set to String.EnumerationOptions.byLines
in order to load the content of a text file line by line into an array:
Foundation
提供String
了一个名为enumerateSubstrings(in:options:_:)
. 下面示出了如何使用代码示例enumerateSubstrings(in:options:_:)
用options
的参数值集合来String.EnumerationOptions.byLines
,以便通过线加载的文本文件行的内容到一个数组:
import Foundation
let path = Bundle.main.path(forResource: "Lorem Ipsum", ofType: "txt")!
let text = try! String(contentsOfFile: path, encoding: String.Encoding.utf8)
let range = text.startIndex ..< text.endIndex
var lines = [String]()
text.enumerateSubstrings(in: range, options: String.EnumerationOptions.byLines) {
(substring, range, enclosingRange, stop) in
guard let substring = substring else { return }
lines.append(substring)
}
print(lines)
#3. Using NLTokenizer
's enumerateTokens(in:using:)
method
#3. usingNLTokenizer
的enumerateTokens(in:using:)
方法
NLTokenizer
has a method called enumerateTokens(in:using:)
. enumerateTokens(in:using:)
has the following declaration:
NLTokenizer
有一个方法叫做enumerateTokens(in:using:)
. enumerateTokens(in:using:)
有以下声明:
@nonobjc func enumerateTokens(in range: Range<String.Index>, using block: (Range<String.Index>, NLTokenizer.Attributes) -> Bool)
Enumerates over a given range of the string and calls the specified block for each token.
在给定的字符串范围内枚举并为每个标记调用指定的块。
The code sample below shows how to use enumerateTokens(in:using:)
in order to load the content of a text file line by line into an array:
下面的代码示例显示了如何将enumerateTokens(in:using:)
文本文件的内容逐行加载到数组中:
import Foundation
import NaturalLanguage
let path = Bundle.main.path(forResource: "Lorem Ipsum", ofType: "txt")!
let text = try! String(contentsOfFile: path, encoding: String.Encoding.utf8)
let tokenizer = NLTokenizer(unit: .paragraph)
tokenizer.setLanguage(.english)
tokenizer.string = text
var lines = [String]()
tokenizer.enumerateTokens(in: text.startIndex ..< text.endIndex) { (range, attributes) -> Bool in
let line = String(text[range])
lines.append(line)
return true
}
print(lines)
回答by j.s.com
This works only until Xcode 6.1 beta 1. In 6.1 beta 2 you must write this:
这仅适用于 Xcode 6.1 beta 1。在 6.1 beta 2 中,您必须这样写:
var err: NSError? = NSError()
let s = String(contentsOfFile: fullPath, encoding: NSUTF8StringEncoding, error: &err)
Where fullPath
is a string containing the full path to the file and NSUTF8StringEncoding
is a predefined constant for UTF8-Encoding.
其中fullPath
是包含文件完整路径的字符串,NSUTF8StringEncoding
是 UTF8 编码的预定义常量。
You can also use NSMacOSRomanStringEncoding
for Mac files or NSISOLatin1StringEncoding
for Windows files.
您还可以NSMacOSRomanStringEncoding
用于 Mac 文件或NSISOLatin1StringEncoding
Windows 文件。
s
is an optional String and you can look if reading the file was successful:
s
是一个可选的字符串,您可以查看读取文件是否成功:
if (s != nil)
{
return (s!) // Return the string as "normal" string, not as optional string
}
回答by hippo_san
If you are in Swift 2.0, you should use:
如果您使用的是 Swift 2.0,则应该使用:
let path = NSBundle.mainBundle().pathForResource(fileName, ofType: nil)
if path == nil {
return nil
}
var fileContents: String? = nil
do {
fileContents = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
} catch _ as NSError {
return nil
}
回答by user3182143
My simple coding for you
我给你的简单编码
let path = NSBundle.mainBundle().pathForResource("FileName", ofType: "txt")
var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!
println(text)
var array = text.componentsSeparatedByString("\n")
回答by Abhishek Jain
Swift 3.0
斯威夫特 3.0
if let path = Bundle.main.path(forResource: <#FileName#>, ofType: "txt")
{
do
{
let str = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
return str.components(separatedBy: "\n")
}
catch
{
}
}
else
{
return nil
}
回答by Alessandro Mattiuzzi
For me works as follow:
对我来说工作如下:
let myFileURL = NSBundle.mainBundle().URLForResource("listacomuni", withExtension: "txt")!
let myText = try! String(contentsOfURL: myFileURL, encoding: NSISOLatin1StringEncoding)
print(String(myText))
回答by Chris Gunawardena
If you want to read a csv file of numeric data. (based on Cezar's answer)
如果要读取数字数据的 csv 文件。(基于 Cezar 的回答)
func get_csv_data() -> [[Double]] {
guard let path = NSBundle.mainBundle().pathForResource("filename_without_extension", ofType: "csv") else {
return []
}
do {
let content = try String(contentsOfFile:path, encoding: NSUTF8StringEncoding)
let line_str_array = content.componentsSeparatedByString("\n")
return line_str_array.map {
let field_str_array = ##代码##.componentsSeparatedByString(",")
return field_str_array.map {
Double(##代码##)!
}
}
} catch _ as NSError {
return []
}
}