C++map应用案例——词频分析

随意给出一段英文文章,测内部单词出现的频率,并按词频降序排序
注:1、不区分大小写
    2、去掉末尾的标点符号

实现,先使用map<string, int>测试各个单词出现的次数,为了使用map<int, string>对词频降序进行排序;另外,在使用for_each进行输出时,使出指定的函数使用函数时编程的lamda表达式。

注:使用了c++11后,auto进行自动类型推导,所以编译需使用c++1y

#include <bits/stdc++.h>
#include <cctype>
using namespace std;
//单词处理
string change_lower(string word)
{
    for(int i = 0; i < word.length(); i++)
    {
        if((word[i] >= 'A') && (word[i] <= 'Z'))
        {
            word[i] = tolower(word[i]); //字符转换成小写
        }
    }
    //去除标点符号
    int len = word.length() - 1;
    if(ispunct(word[len]))
    {
        string::iterator it = word.end() - 1;
        word.erase(it);
    }
    return word;
}
//数据处理
void deal_data()
{
    map<string, int> word_count;
	multimap<int, string, greater<int> > count;
    string word;
    ifstream in("english.txt");
    while(in >> word)
    {
        word = change_lower(word);
        word_count[word]++;
    }

    for(map<string,int>::iterator it = word_count.begin();
        it != word_count.end(); it++)
    {
        count.insert(make_pair(it->second, it->first));
    }
	for_each(count.begin(), count.end(), [](auto t1){
		cout << t1.second << "-----》count: " << t1.first << endl;
	}
	);
}

int main(void)
{
    deal_data();
    return 0;
}

map<string, int>注意事项:

map实现的事情就是让所有的类型都可以做下标。

map<string, int> word_count;
cout << ++word_count["string"] << endl;
//注:在map中加入一个字符串后,该字符串的个数就为1;开始时,int默认为0

本次使用中,c++11lamda表达式使用有些生疏,需要尽快巩固

发布了125 篇原创文章 · 获赞 6 · 访问量 5180

猜你喜欢

转载自blog.csdn.net/weixin_42067873/article/details/103075478