我有一個非常復雜的字串,看起來像:
{infobox Country
|country = France
|map = <map lat='47' lng='1.5' zoom='5' view='0' height='320' country='France'/>
|language = French (regional languages: Alsatian, Occitan, Breton, Corsican, Basque, Catalan, ...)
|capital = [[Paris]]
|pop = 65,8 million
|currency = Euro (€)
|hitch = <rating country='fr' />
|BW = FR
}
我想要做的是提取資料,理想情況下是字典的格式,讓我們說“國家”是一個鍵,“法國”是一個值。任何其他鍵的方式相同。
我該如何解決這個問題?我唯一的想法是通過使用一些字串切片和使用索引來做到這一點,但這感覺是一種糟糕的方法。必須有一些更好的方法來做到這一點。有什么方法可以像 json 檔案那樣進行建模嗎?
uj5u.com熱心網友回復:
如果您擁有的是結構化文本,并對其含義進行了正式定義,那么您所看到的是一種語言,而這只是為該語言撰寫決議器的一種情況。決議器是可以將輸入字串轉換為 T 或描述錯誤的函式。有很多不同的方法來撰寫決議器,(從字串映射到其他資料型別非常常見)但也許最好的一種是決議器組合器,這個主題已經被 objc.io 和 pointfree.co 涵蓋
uj5u.com熱心網友回復:
我首先將它拆分為“|” 然后使用第一個“=”作為分隔符創建鍵/值對
//Drop the surrounding {} and split the text on |
let rows = input.dropFirst().dropLast().split(separator: "|")
第一個元素“資訊框...”的特殊情況
let title = rows.first
然后使用reduce創建字典
let dictionary = rows.dropFirst().reduce(into: [String:String]()) {
guard let index = $1.firstIndex(of: "=") else { return }
let key = String($1[$1.startIndex..<index]).trimmingCharacters(in: .whitespaces)
let value = String($1[$1.index(after: index)..<$1.endIndex]).trimmingCharacters(in: .whitespacesAndNewlines)
$0[key] = value
}
print(title ?? "")
print(dictionary)
infobox Country
["capital": "[[Paris]]", "language": "法語(地區語言:阿爾薩斯語、奧克西坦語、布列塔尼語、科西嘉語、巴斯克語、加泰羅尼亞語等)", "map": "<map lat='47' lng='1.5' zoom='5' view='0' height='320' country='France'/>", "BW": "FR", "pop": "65,8百萬", "country": "France", "currency": "Euro (€)", "hitch": "<rating country='fr' />"]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/317708.html
