swift 計算單詞數(shù)組的詞頻

'''
//
// MainViewController.swift
// Test
//
// Created by Nick on 2020/7/16.
// Copyright ? 2020 Nick. All rights reserved.
//

import UIKit

class MainViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = UIColor.white
    
    let car:Goods = Goods.init(name: "BMW X5", price: 100.0)
    car.addCount(count: 33)
    car.reduceCount(count: 4)
    car.showTotalPrice()
    
    let wordAnalysis:WordAnalysis = WordAnalysis.init(fileName: "abs")
    let dict = wordAnalysis.analysisWordFrequency()
    
    let after = dict.sorted { (arg0, arg1) -> Bool in
        if(arg0.value > arg1.value) {
            return false
        }
        return true
    }.reversed()
    
    for (key, value) in after {
        print("單詞 \(key) 出現(xiàn)過 \(value) 次")
    }
    
    wordAnalysis.getTheMostCountAppearAdjacentByWord()
}

}

class Goods: NSObject {

var name:String = ""
var price:Double = 0.0
var goodsCount:Int = 0
var totalPrice:Double = 0.0

var cheap_1000:Double = 100.0
var cheap_500:Double = 50.0

init(name:String, price:Double) {
    super.init()
    self.name = name
    self.price = price
}


func addCount(count:Int){
    self.goodsCount += count
}

func reduceCount(count:Int){
    if self.goodsCount >= count {
        self.goodsCount -= count
    }else{
        self.goodsCount = 0
    }
}

func showTotalPrice(){
    let price:Double = Double(self.goodsCount) * self.price
    let cheap_1000_count:Int = Int(price / 1000)
    
    let remainPrice:Double = price - Double(cheap_1000_count) * cheap_1000
    let cheap_500_count:Int = Int(remainPrice / 500)
    
    let cheapPrice:Double = Double(cheap_1000_count)*cheap_1000 + Double(cheap_500_count)*cheap_500
    totalPrice = price - cheapPrice
    
    print("商品:\(self.name) \n數(shù)量:\(self.goodsCount) \n原價:\(price)\n優(yōu)惠金額:\(cheapPrice)\n實收\(totalPrice)")
}

}

class WordAnalysis: NSObject {

var fileName:String = ""

init(fileName:String) {
    super.init()
    self.fileName = fileName
}

//獲取文件中的單詞數(shù)組
func getWordsInFile() -> Array<String>{
    let path = Bundle.main.url(forResource: self.fileName, withExtension: "txt")
    let data = try! Data(contentsOf: path!)
    guard let fileContentString = String(data: data, encoding: .utf8)
        else {
            print("Read file content failed !")
            return []
    }
    
    let letterSet:String = "abcdefghijklmnopqrstuvwxyz "
    
    let filteredCharacters = fileContentString.filter {
        return NSString(string: letterSet).contains(String($0))
    }
    let filteredString = String(filteredCharacters)
    
    let wordArr = filteredString.components(separatedBy: " ").filter { $0.count > 0 }
    return wordArr
    
}

//獲取一個單詞數(shù)組中單詞的詞頻
@discardableResult func analysisWordFrequency() -> Dictionary<String, Int>{
    var wordFrequencyDic:Dictionary<String, Int> = Dictionary.init()
    
    let arr:Array<String> = self.getWordsInFile()
    for word:String in arr {
        let keys = wordFrequencyDic.keys
        if keys.contains(word) {
            wordFrequencyDic[word] =  wordFrequencyDic[word]! + 1
        }else{
            wordFrequencyDic[word] =  1
        }
    }
    return wordFrequencyDic
}

//獲取數(shù)組中每一個單詞相鄰的單詞中出現(xiàn)次數(shù)最多的兩個單詞
func getTheMostCountAppearAdjacentByWord() {
    
    let arr = self.getWordsInFile()
    let words:Dictionary<String, Int> = self.analysisWordFrequency()
    
    for word in words.keys {
        
        var dict:Dictionary<String, Int> = [:]
        
        for (index, value) in arr.enumerated() {
            if  word == value {
                if index == 0 {
                    let adjacentWord = arr[index + 1]
                    dict = updateWordCountInDictionary(dict: dict, word: adjacentWord)
                }else if index == arr.count - 1 {
                    let adjacentWord = arr[index - 1]
                    dict = updateWordCountInDictionary(dict: dict, word: adjacentWord)
                }else {
                    let adjacentLeftWord = arr[index - 1]
                    dict = updateWordCountInDictionary(dict: dict, word: adjacentLeftWord)
                    let adjacentRightWord = arr[index + 1]
                    dict = updateWordCountInDictionary(dict: dict, word: adjacentRightWord)
                }
            }
        }
        let after = dict.sorted { (arg0, arg1) -> Bool in
            if(arg0.value < arg1.value) {
                return false
            }
            return true
        }
        print("\(word)的相鄰單詞中\(zhòng)n \(after[0].key):\(after[0].value)次\n \(after[1].key):\(after[1].value)次")
    }
}

func updateWordCountInDictionary(dict:Dictionary<String, Int>, word:String) -> Dictionary<String, Int> {
    var dictionary:Dictionary<String, Int> = dict
    if dictionary.keys.contains(word) {
        dictionary[word] = dictionary[word]! + 1
    }else{
        dictionary[word] = 1
    }
    return dictionary
}

}

'''

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末但两,一起剝皮案震驚了整個濱河市艰猬,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖活孩,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件痹仙,死亡現(xiàn)場離奇詭異沿彭,居然都是意外死亡瞻鹏,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進(jìn)店門捺萌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來档冬,“玉大人,你說我怎么就攤上這事互婿〉方迹” “怎么了?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵慈参,是天一觀的道長呛牲。 經(jīng)常有香客問我,道長驮配,這世上最難降的妖魔是什么娘扩? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任着茸,我火速辦了婚禮,結(jié)果婚禮上琐旁,老公的妹妹穿的比我還像新娘涮阔。我一直安慰自己,他們只是感情好灰殴,可當(dāng)我...
    茶點故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布敬特。 她就那樣靜靜地躺著,像睡著了一般牺陶。 火紅的嫁衣襯著肌膚如雪伟阔。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天掰伸,我揣著相機(jī)與錄音皱炉,去河邊找鬼。 笑死狮鸭,一個胖子當(dāng)著我的面吹牛合搅,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播歧蕉,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼灾部,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了廊谓?” 一聲冷哼從身側(cè)響起梳猪,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤麻削,失蹤者是張志新(化名)和其女友劉穎蒸痹,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體呛哟,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡叠荠,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了扫责。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片榛鼎。...
    茶點故事閱讀 39,919評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖鳖孤,靈堂內(nèi)的尸體忽然破棺而出者娱,到底是詐尸還是另有隱情,我是刑警寧澤苏揣,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布黄鳍,位于F島的核電站,受9級特大地震影響平匈,放射性物質(zhì)發(fā)生泄漏框沟。R本人自食惡果不足惜藏古,卻給世界環(huán)境...
    茶點故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望忍燥。 院中可真熱鬧拧晕,春花似錦、人聲如沸梅垄。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽队丝。三九已至蔫敲,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間炭玫,已是汗流浹背奈嘿。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留吞加,地道東北人裙犹。 一個月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像衔憨,于是被迫代替她去往敵國和親叶圃。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,864評論 2 354