2016-02-26 149 views
0

我做了一個[String: [String]]類型的字典。這些值代表一個名稱列表,而鍵代表所有這些名稱的首字母。得到它了?Unicode特殊字符轉換

好的。現在我可以通過檢測它們的第一個字母的算法將名稱附加到它們的鍵陣列。這是我的問題開始的地方。我想將以特殊字符開頭的名稱放入"O"-key-array,例如"Ø"

事情是這樣的:

"Øder" ----->算法檢測第一個字母------>["0": ["Øder", ...]]

我的方法是第一個字母轉換爲它們的Unicode和檢查它是一個特殊字符並將其轉換爲相關的拉丁字母。

這是要走的路,還是我沒有考慮過的更簡單的解決方案?

+6

你爲什麼要爲Python和Swift標記這個問題? –

+0

也,你使用python2或3? – timgeb

+0

在Python中,您可以使用['unidecode'](https://pypi.python.org/pypi/Unidecode)將字符轉換爲最接近的ASCII等效字符。 –

回答

0

這斯威夫特效果很好:

let names = ["test", "another", "two", "øder"] 

let index = names.reduce([Character: [String]]()) { 
    (var initial: [Character: [String]], current: String) -> [Character: [String]] in 
    if let first = current.characters.first 
    where initial[first]?.append(current) == nil { 
     initial[first] = [current] 
    } 

    return initial 
} 

print(index) // -> ["ø": ["øder"], "t": ["test", "two"], "a": ["another"]] 

遺憾的是我沒能找到Unicode字符轉換爲一個簡單的ASCII格式的任何功能。也許某種字典可以用這種映射創建。

+0

沒問題,很樂意幫忙。當然,它可以被改進以更好地處理大寫和小寫,符號,Unicode字形等。 – ColGraff