2012-03-11 67 views
0

我GOOGLE了這個問題,並找不到一個答案,與我的代碼工作,所以我寫這個來獲取單詞的頻率唯一的問題是,我得到錯誤的數字除了形成一個我認爲是僥倖的詞彙之外。此外,我正在檢查,看看一個單詞是否已經進入矢量,所以我不計算兩次相同的單詞。獲取Word頻率從矢量在C++

fileSize = textFile.size(); 
vector<wordFrequency> words (fileSize); 
int index = 0; 
for(int i = 0; i <= fileSize - 1; i++) 
{ 
    for(int j = 0; j < fileSize - 1; j++) 
    { 
     if(string::npos != textFile[i].find(textFile[j]) && words[i].Word != textFile[j]) 
     { 
      words[j].Word = textFile[i]; 
      words[j].Times = index++; 
     } 
    } 
    index = 0; 
} 

任何幫助,將不勝感激。

+0

您是否獲得了比預期更多的事件?你的程序中的文本文件的查找成員函數做什麼? – bhuwansahni 2012-03-11 11:37:31

+0

@bhuwansahni是的,我得到一個是正確的。 find是一個查找匹配字符串的向量函數。 – bobthemac 2012-03-11 11:40:06

+0

什麼發現失敗和成功的回報? – bhuwansahni 2012-03-11 11:45:53

回答

1

試試這個代碼,而不是如果你不想使用地圖容器..

struct wordFreq{ 
    string word; 
    int count; 
    wordFreq(string str, int c):word(str),count(c){} 
    }; 
vector<wordFreq> words; 

int ffind(vector<wordFreq>::iterator i, vector<wordFreq>::iterator j, string s) 
{ 
    for(;i<j;i++){ 
     if((*i).word == s) 
      return 1; 
    } 
    return 0; 
} 

代碼查找沒有出現在一個文本載體則是:

for(int i=0; i< textfile.size();i++){ 
    if(ffind(words.begin(),words.end(),textfile[i])) // Check whether word already checked for, if so move to the next one, i.e. avoid repetitions 
     continue; 
    words.push_back(wordFreq(textfile[i],1));   // Add the word to vector as it was not checked before and set its count to 1 
    for(int j = i+1;j<textfile.size();j++){   // find possible duplicates of textfile[i] 
     if(file[j] == (*(words.end()-1)).word) 
      (*(words.end()-1)).count++; 
    } 
} 
+0

需要一點調整,但現在得到它的工作感謝幫助。 – bobthemac 2012-03-11 14:02:07

+1

哎喲...這很尷尬!使用'map'或'unordered_map'類更簡單! – 2012-03-11 14:11:30

+0

是啊使用地圖會好得多,但如果你不想使用它... – bhuwansahni 2012-03-11 17:10:46

2

請考慮使用std::map<std::string,int>代替。地圖類將處理確保你沒有任何重複。

2

使用的關聯容器:

typedef std::unordered_map<std::string, unsigned> WordFrequencies; 

WordFrequencies count(std::vector<std::string> const& words) { 
    WordFrequencies wf; 
    for (std::string const& word: words) { 
    wf[word] += 1; 
    } 
    return wf; 
} 

這是很難得簡單...

注:您可以map取代unordered_map,如果你想在世界上按字母順序排序,你可以編寫自定義的比較操作對待他們不區分大小寫。