gpt4 book ai didi

ios - 在 Swift 3.0 中使用 NSDataDetector 从字符串中提取地址元素

转载 作者:搜寻专家 更新时间:2023-10-30 22:32:35 26 4
gpt4 key购买 nike

我正在尝试使用 NSDataDetector 从字符串中找到地址。我看过NSHipster's article on NSDataDetector以及Apple's NSDataDetector documentation .我有以下方法可以从字符串中提取地址:

func getAddress(from dataString: String) -> [String] {
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.address.rawValue)
let matches = detector.matches(in: dataString, options: [], range: NSRange(location: 0, length: dataString.utf16.count))

var addressArray = [String]()

// put matches into array of Strings
for match in matches {
let address = (dataString as NSString).substring(with: match.range)
addressArray.append(address)
}

return addressArray
}

我想提取地址元素,而不是整个地址。在 NSHipster's NSDataDetector postData Detector Match Types 部分,我看到地址组件,例如 NSTextCheckingCityKey , NSTextCheckingStateKey , 和 NSTextCheckingZIPKey .我无法在 NSDataDetector 的初始化中使用这些键。

我在 GitHub 上四处寻找,看看是否可以找到一个示例作为借鉴,但我唯一能找到的东西是 Objective-C 代码或主 Swift 存储库中的声明性东西。

我有 99% 的把握可以提取地址的各个组成部分,但我太笨了,搞不懂。感谢您阅读。我欢迎提出建议。

最佳答案

我以前没有用过这个类,但看起来它返回类型为 NSTextCheckingResult 的对象。如果您得到类型为 NSTextCheckingTypeAddress 的结果,那么您可以询问结果是否为 addressComponents,这将是一个包含地址不同部分的字典。

编辑:

这是我刚刚敲出的一些工作 Playground 代码:

import UIKit

var string = "Now is the time for all good programmers to babble incoherently.\n" +
"Now is the time for all good programmers to babble incoherently.\n" +
"Now is the time for all good programmers to babble incoherently.\n" +
"123 Elm Street\n" +
"Daton, OH 45404\n" +
"Now is the time for all good programmers to babble incoherently.\n" +
"2152 E Street NE\n" +
"Washington, DC 20001"

let results = getAddress(from: string)

print("matched \(results.count) addresses")
for result in results {
let city = result[NSTextCheckingCityKey] ?? ""
print("address dict = \(result).")
print(" City = \"\(city)\"")
}

func getAddress(from dataString: String) -> [[String: String]] {
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.address.rawValue)
let matches = detector.matches(in: dataString, options: [], range: NSRange(location: 0, length: dataString.utf16.count))

var resultsArray = [[String: String]]()
// put matches into array of Strings
for match in matches {
if match.resultType == .address,
let components = match.addressComponents {
resultsArray.append(components)
} else {
print("no components found")
}
}
return resultsArray
}

此代码打印:

matched 2 addresses

address dict = ["Street": "123 Elm Street", "ZIP": "45404", "City": "Daton", "State": "OH"]. City = "Daton"

address dict = ["Street": "2152 E Street NE", "ZIP": "20001", "City": "Washington", "State": "DC"]. City = "Washington"

关于ios - 在 Swift 3.0 中使用 NSDataDetector 从字符串中提取地址元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41077174/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com