簡體   English   中英

計算向量中的單詞出現<string>

[英]Counting word occurrences in vector<string>

我得到了這份家庭作業,在其中我必須制作一個可以使用參數從cmd調用的c ++應用程序。 有3個參數:

第一個將所有不帶標點的單詞轉換為小寫並按字母順序存儲。 所以我使用了向量字符串。

第二個單詞對文件中每個單詞的出現進行計數,並對它們進行排序,以便最常用的單詞排在第一位。 我被困在這部分,不知道如何處理..所以,如果有人可以幫助我,我將非常感激

第三個參數計算每個標點符號的出現..與上面相同,正如您所看到的,我也停留在這一部分哈哈。這是到目前為止的代碼:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>


using namespace std;


int main(int argc, char* argv[])
{
ifstream ulaz ("korpus.txt");
string testline;
vector<string> word;

if (string(argv[1])=="-r"){
    cout<<"uzima rijeci iz korpusa i stavlja u rijecnik po abecedi"<<endl;
    while(ulaz >> testline)
    {
        for(int i=0; i<testline.size(); i++){
                if (ispunct(testline[i])) testline.erase(i);
        }
    transform (testline.begin(), testline.end(), testline.begin(), ::tolower);
    word.push_back(testline);
    }
    sort(word.begin(), word.end());
    for (int i=0; i<word.size(); i++) {
            cout<<word[i]<<"("<<i<<")"<<endl;
    }
}


if (string(argv[1])=="-f"){
    cout<<endl<<"frekventonost ponavljanja se izračunava"<<endl;
}
if (string(argv[1])=="-i"){
    cout<<endl<<"broj interpunkcija i sranja se izračunava"<<endl;

}
return 0;
}

您可以使用map或unordered_map進行文字計數器:

std::map<std::string, unsigned int> counter;
for (auto w : word)
{
    counter[w]++;
}

然后,您只需要按計數對地圖的元素進行排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM