我已经尝试为您的问题找到解决方案,
这是JSON response
我用作示例的,
[
{
"confidence": "<null>",
"end": 113,
"entity": "DATE",
"extractor": "ner_spacy",
"start": 103,
"value": "five years"
},
{
"confidence": "<null>",
"end": 177,
"entity": "ORG",
"extractor": "ner_spacy",
"start": 163,
"value": "xyz Company"
}
]
JSON response
将using解析Codable
为array of Entity
对象,即
struct Entity: Codable {
var confidence: String?
var end: Int?
var entity: String?
var extractor: String?
var start: Int?
var value: String?
}
我entity key
在响应中使用来确定要替换的值,即
if let data = str.data(using: .utf8) { //You'll get this data from API response
let entities = try? JSONDecoder().decode([Entity].self, from: data)
var sentence = "In your {{DATE}} of experience at {{ORG}}, what kind of process improvements or standards setup?"
entities?.forEach({
if let entity = $0.entity, let value = $0.value {
sentence = sentence.replacingOccurrences(of: "{{\(entity)}}", with: value)
}
})
print(sentence) //In your five years of experience at xyz Company, what kind of process improvements or standards setup?
}
在上面的代码中,我遍历了entities array
并将每次出现的 替换{{entity}}
为相应的value
,即
"{{DATE}}" is replaced with "five years"
"{{ORG}}" is replaced with "xyz Company"
如果您仍然遇到任何问题或者我没有很好地理解问题陈述,请告诉我。