使用map数据结构统计词频

数据结构字典(map)

map数据结构在各种语言里面都有者自己的实现。

nodejs里面的对象本身就是一个键值对形式,虽然nodejs里面有Map类,不过我们也可以直接用对象进行map操作。

c++的stl标准库历尽无数的考验,无论是性能,还是稳定性都有保证,我们可以直接使用里面的数据结构。

java有map接口,我们可以选择TreeMap或者HashMap去进行词频统计。他们之间的区别是TreeMap会根据传入的key进行排序,底层使用红黑树排序,节约空间。HashMap底层使用数组,查找,删除,增加快,但是会消耗空间。读者可以根据自己的场景选择合适的数据结构。

golang有天生自带的数据结构,数组和字典是golang自带的数据结构。Map 是无序的,我们无法决定它的返回顺序,这是因为 Map 是使用 hash 表来实现的。

下面我将演示用这四种语言的map统计词频。

nodejs

let string = 'I like apple,do you like apple' //测试语句

string = string.split(/[ ,]/) //正则表达式用空格和逗号分割字符串

console.log('分割后,字符串数组为:',string)

/*****使用obj统计词频******/
let obj={}

for(let str of string){
    if((obj[str]|0)===0){
        obj[str]=1
    }else{
        obj[str]=obj[str]+1
    }
}

console.log(obj)
/******************

{ I: 1, like: 2, apple: 2, do: 1, you: 1 }
可以看到,已经统计好词频了

******************/

c++

#include<iostream>
#include<map>
#include<string>
#include<vector>
using namespace std;
int main(){

    string sentance ="I like apple,do you like apple";//测试语句

    vector<string> words ;//声明字符串数组

    int start=0,end=0;

 /***************分割字符串*****************/
    for(int i=0;i<sentance.size();i++){
        if(sentance[i]==' '||sentance[i]==','){
            end=i;
            if(end!=start)
            words.push_back(sentance.substr(start,end-start));
            start=i+1;
        }else if(i==sentance.size()-1){
            end=i;
            words.push_back(sentance.substr(start,end-start+1));
        }
    }

 /*************遍历字符串****************/
    for(string str:words){
        cout<<"word:"<<str<<endl;
    }

    cout<<"*********************"<<endl;//分割符

    map<string,int> dict;//声明字典

    for(string word:words){

        dict[word]++; //统计词频

    }

    for(auto it : dict){

       cout<<"key:"+it.first+" value:"<<it.second<<endl;//遍历字典

   }

}





 

 

java


public class TestApp {
    public static void main(String[] args) {
        String sentance = "I like apple,do you like apple";//测试字符串
        String []words=sentance.split("[ ,]");
        System.out.println("分割字符串");
        for(String word:words){
            System.out.println(word);
        }

        Map<String,Integer> map= new HashMap<>();
        for(String word:words){
            map.put(word,map.getOrDefault(word,0)+1);
        }

        System.out.println("遍历字典");

        for(String key:map.keySet()){
            System.out.println(key+":"+map.get(key));
        }
    }
}

 

 

 golang

package main

import (
	"fmt"
	"strings"
)
//自定义分割函数
func split(r rune) bool {
	return r == ' ' || r == ','
}

func main() {
    //测试语句
	str := "I like apple,do you like apple"
	words := strings.FieldsFunc(str, split)
	for _, value := range words {
		fmt.Println(value)
	}

	m := make(map[string]int)

	for _, value := range words {
		m[value]++
	}

	for key, value := range words {
		fmt.Println(key)
		fmt.Println(value)
	}
}

 

经过笔者的对比,各种语言之间各有千秋。nodejs比较简短,适合操作字符串,c++分割字符串需要手动实现,不过map数据结构的实现比较简单,非常方便调用。Java不用说了,相信很多人用的比我还要溜。golang语言语法跟c差不过,风格简单。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现词频统计的一种简单方法是使用Java中的HashMap数据结构,将每个单词作为键,出现次数作为值。具体实现步骤如下: 1. 读取文本文件,将文件内容存储在一个字符串中。 2. 使用正则表达式将字符串中的非字母字符替换为空格,以便将文本分割成单词。 ```java String content = readFileAsString("input.txt"); // 读取文本文件 content = content.replaceAll("[^a-zA-Z]", " "); // 将非字母字符替换为空格 ``` 3. 将文本分割成单词,并统计每个单词出现的次数。 ```java Map<String, Integer> wordCount = new HashMap<>(); String[] words = content.split("\\s+"); for (String word : words) { word = word.toLowerCase(); // 将单词转换为小写字母,以便不区分大小写 if (!word.isEmpty()) { int count = wordCount.getOrDefault(word, 0); wordCount.put(word, count + 1); } } ``` 4. 输出每个单词及其出现次数。 ```java for (String word : wordCount.keySet()) { int count = wordCount.get(word); System.out.println(word + ": " + count); } ``` 完整代码如下: ```java import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; public class WordCount { public static void main(String[] args) throws IOException { String content = readFileAsString("input.txt"); // 读取文本文件 content = content.replaceAll("[^a-zA-Z]", " "); // 将非字母字符替换为空格 Map<String, Integer> wordCount = new HashMap<>(); String[] words = content.split("\\s+"); for (String word : words) { word = word.toLowerCase(); // 将单词转换为小写字母,以便不区分大小写 if (!word.isEmpty()) { int count = wordCount.getOrDefault(word, 0); wordCount.put(word, count + 1); } } for (String word : wordCount.keySet()) { int count = wordCount.get(word); System.out.println(word + ": " + count); } } private static String readFileAsString(String filePath) throws IOException { return new String(Files.readAllBytes(Paths.get(filePath))); } } ``` 其中,`readFileAsString`方法用于读取文本文件并返回字符串。如果需要统计多个文件的词频,可以将整个统计过程放到一个循环中,每次读取一个文件并更新词频统计结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值