美文网首页
swift 计算单词数组的词频

swift 计算单词数组的词频

作者: 觅渡丶 | 来源:发表于2020-07-20 12:38 被阅读0次

    '''
    //
    // 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) 出现过 \(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数量:\(self.goodsCount) \n原价:\(price)\n优惠金额:\(cheapPrice)\n实收\(totalPrice)")
    }
    

    }

    class WordAnalysis: NSObject {

    var fileName:String = ""
    
    init(fileName:String) {
        super.init()
        self.fileName = fileName
    }
    
    //获取文件中的单词数组
    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
        
    }
    
    //获取一个单词数组中单词的词频
    @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
    }
    
    //获取数组中每一个单词相邻的单词中出现次数最多的两个单词
    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)的相邻单词中\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
    }
    

    }

    '''

    相关文章

      网友评论

          本文标题:swift 计算单词数组的词频

          本文链接:https://www.haomeiwen.com/subject/ydiekktx.html