【第一周】c++實現詞頻統計


coding.net地址:https://coding.net/u/Boxer_

ssh:git@git.coding.net:Boxer_/homework.git

--------------------------------------------------------------------------------------

9.6更新了一下,按老師要求把程序分塊發表了,git版本控制內容比較多,正在學(2016.9.9已學)。

--------------------------------------------------------------------------------------

需求:從一個英文txt中讀取內容,實現詞頻統計。

現完成:基本功能大概完成了,由於編程基礎比較差,文件操作部分還不是很熟練,我發現從文件中提取字符串流讀取到程序的string對象中,會把所有的空格過濾掉,導致沒法統計單詞頻率,目前還沒找到解決方法,只能先手動輸入文章了。ORZ...

好好學習java,目前看來,處理字符串等問題還是java有成熟的解決方案。

1.建立一個word類,包含str和count兩個屬性,分別代表word的內容和個數。包含一個exchange方法,用來交換兩個word的內容。

 

class Word
{
    public:
    Word() : Str(""), Count(0)
    {}
    string Str;
    int Count;
    void exchange(Word &word)
    {
        string tStr = word.Str;
        int tCount = word.Count;
        word.Str = Str;
        word.Count = Count;
        Str = tStr;
        Count = tCount;
    }
};

 

2.用來統計單詞的個數。

 

void CalcCount(Word * words, string &newWord, int size)
{
    int i = 0;
    for(; i < size; i++)
    {
        if(words[i].Str == newWord)
        {
            words[i].Count++;
            return;
        }
        else if(words[i].Str == "")
            break;
    }
    words[i].Str = newWord;
    words[i].Count = 1;
}

 

3.用來進行單詞排序,采用冒泡算法。

 

void SortWordDown(Word * words, int size)
{
    for(int i = 0; i < size; i++)
    {
        for(int j = 0; j < size-1; j++)
        {
            if(words[j].Count <  words[j+1].Count)
            {
                words[j].exchange(words[j+1]);
            }
        }
    }
}

 

4.主函數

int main()
{
    Word * words;
    string content;
    cout << "輸入一段英文:";
    getline(cin, content);

    //計算單詞總數
    int wCount = 1;
    for(unsigned int i = 0; i < content.length(); i++)
    {
        if(content[i] == ' ')
            wCount++;
    }
    words = new Word[wCount];

    string::size_type offset = content.find(' ');//單詞都是以空格隔開
    while(offset != string::npos)
    {
        string wStr = content.substr(0, offset);
        content.erase(0, offset+1);
        CalcCount(words, wStr, wCount);
        offset = content.find(' ');
    }
    CalcCount(words, content, wCount);//計算最后一個單詞

    SortWordDown(words, wCount);
    int printCount = wCount ;
    
    for(int i = 0; i < printCount; i++)
    {
        cout << words[i].Str << "\t" << words[i].Count <<  endl;
    }

    delete [] words;
    return 0;
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM