读入一个文本,确定所有单词的使用频率并从高到底排序,打印出所有单词以及其频率列表
先不解决频率问题 先看下不使用高阶函数
//: A UIKit based Playground for presenting user interface
import UIKit
//去掉一些语气次 不加入计算
let NON_WORDS:Set = ["the","and","of","to","a","i","it","in","or","is","as","so","but","be"]
//传统解决方法
func wordFreq(words:String)->[String:Int]{
var wordDict:[String:Int]=[:]
let wordList=words.split(separator: " ")
for word in wordList{
let lowerCaseWord=word.lowercased()
if !NON_WORDS.contains(lowerCaseWord){
if let count = wordDict[lowerCaseWord]{
wordDict[lowerCaseWord] = count+1
}else{
wordDict[lowerCaseWord]=1
}
}
}
return wordDict;
}
let words="""
There are moments in life when you miss someone so much that you just want to pick them from your dreams and hug them for real!
"""
print(wordFreq(words: words))
["there": 1, "pick": 1, "them": 2, "your": 1, "for": 1, "dreams": 1, "hug": 1, "when": 1, "real!": 1, "that": 1, "you": 2, "are": 1, "life": 1, "miss": 1, "just": 1, "moments": 1, "from": 1, "much": 1, "want": 1, "someone": 1]
使用高级函数
//: A UIKit based Playground for presenting user interface
import UIKit
//去掉一些语气次 不加入计算
let NON_WORDS:Set = ["the","and","of","to","a","i","it","in","or","is","as","so","but","be"]
//函数编程
func wordFreq(words:String)->[String:Int]{
var wordDict:[String:Int]=[:]
let wordList=words.split(separator: " ")
wordList.map {$0.lowercased()}
.filter{ !NON_WORDS.contains($0)}
.forEach{(word) in
wordDict[word]=(wordDict[word] ?? 0)+1
}
return wordDict;
}
let words="""
There are moments in life when you miss someone so much that you just want to pick them from your dreams and hug them for real!
"""
print(wordFreq(words: words))
排序很简单
wordDict.sorted {$0.1 > $1.1}
业务需求
假设我们有一个名字列表,其中一些条目由单个字符构成。现在的任务是,将出去单字符之外的列表内容,放在一个逗号分割的字符串里返回,且每个名字的首字母都要大写
命令式解法
传统for循环:
//: A UIKit based Playground for presenting user interface
import UIKit
let emlpyee = ["neal","s","stu","j","rich","bob","aiden","j","ethan"]
func cleanNamaes(names:Array<String>)->String{
var clearnedNames = ""
for name in names{
if name.count>1{
clearnedNames += name.capitalized + ","
}
}
clearnedNames.remove(at: clearnedNames.index(before: clearnedNames.endIndex))
return clearnedNames
}
let res=cleanNamaes(names: emlpyee)
print(res)
高阶函数
let res2=emlpyee.filter{ $0.count>1 }
.map{ $0.capitalized }
.joined(separator: ",")
结果
Neal,Stu,Rich,Bob,Aiden,Ethan
标签:them,函数,编程,let,words,wordDict,swift,clearnedNames,String From: https://blog.51cto.com/u_14523369/6113217