gpt4 book ai didi

c++ - 使用 C++ 映射来计算词频。我究竟做错了什么?

转载 作者:行者123 更新时间:2023-11-30 02:29:42 24 4
gpt4 key购买 nike

所以有点背景。我应该制作一个程序,逐行检查一个段落,并在每一行中挑选出最常用的单词。我已经有效地编写了将一行内容存储在 vector 中的代码,现在我需要将频率分配给这些词。我正在使用 map ,但它没有给我想要的结果。我是 C++ 数据结构的新手,所以我将不胜感激。

map<string,int> freq;   //map for getting frequency on line

for(int i=0;i<currLine.size();i++){ //loops through the words on the line


string currName=currLine.at(i); //current word
//cout<<currName<<endl;
if(freq.find(currName)!=freq.end()){ //if already present

int update=freq.at(currName)+1; //this value takes the value and adds one
freq.insert(pair<string,int>(currName,update)); //insert back into the string with updated value
//cout<<freq.at(currName);
}
else{
freq.insert(pair<string,int>(currName,0)); //if not present, then insert with value 0
}
}

例如:

- 与您不同,我对 gnu 感到不满。不介意我把食物带走吗?乔治·奥威尔 (George Orwell) 对 1984 年的看法是错误的。你的猫会编码吗?如果不会,你的狗会编码吗?我喜欢玩辐射游戏。推荐你也玩。足球是美国以外最受欢迎的运动。

会返回:“不像我,乔治会踢足球”

    int main()
{
string line;
vector<string> result;
while(getline(cin,line)){ //on each line
vector<string> currLine; //stores words on line
string curr=""; //temp string for grasping words
for(int i=0;i<line.length();i++){ //loops through line
if(isalpha(line.at(i))){ //if it is a letter, add it to the temp string
curr+=tolower(line.at(i));
}
else if(line.at(i)=='\''){
//do nothing
}
else{ //if not, then add the previous word to vector and reset temp string
currLine.push_back(curr);
curr="";
}
}



vector< pair<string, int> > freq(10);
//freq.push_back(make_pair("asd",2));
for(int i=0;i<currLine.size();i++){
string curr1=currLine.at(i);
cout<<curr1<<" ";
for(int j=0;j<freq.size();j++){
if(freq.at(j).first==curr1){ //if present in the list
//cout<<"Duplicate found";
freq.at(j).second++; //increment second value
}
else{
//cout<<"Pair Made";
freq.push_back(make_pair(curr1,1));
break;
}
}
}

int max=0;
string currMost;
for(int i =0;i<freq.size();i++){

if(freq.at(i).second>max){
max=freq.at(i).second;;
currMost=freq.at(i).first;
}
}
//cout<<currMost;

cout<<endl;



// result.push_back(currMost);

}

for(int i=0;i<result.size();i++){
cout<<result.at(i);
}

}

最佳答案

我先把句子拆分成单词,然后存入map。插入 map 的最简单和更明显的方法是使用 map[key] = value 表示法。我首先使用 count() 函数检查该值是否已经存在并插入该值,否则我会增加已经存在的键的值。

map <string, int> word_frequency;
string word="";
for (int i=0; i<=current_line.length();i++) {
if (current_line[i]!=' ' && i< current_line.length()) {
word = word + current_line[i];
} else if(word_frequency.count(word) == 0) {
word_frequency[word] = 1;
word = "";
} else {
word_frequency[word]++;
word = "";
}
}

关于c++ - 使用 C++ 映射来计算词频。我究竟做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39314375/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com