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)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容