【Programming Pearls】對文檔中的單詞進行計數問題

所謂單詞就是用空格分隔開的字符序列。但是在網頁文件中還包含&nbsp;<html>等詞,所以需要避免這種情況。

 

示例 1:
int main(void)
{ set S;
set::iterator j;
string t;
while (cin >>t) //讀取輸入,插入到set集合S中,重複的單詞忽略
S.insert(t);
for (j = S.begin();j != S.end(); ++j)
cout << *j<< "\n"; //按順序輸出單詞
return 0;
}

下面我們將統計一個文檔中各個單詞出現的頻率。

可以採用C++中的STL map容器來實現:

示例2:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{ map<string, int> M;
map<string, int>::iterator j;
string t;
while (cin >> t)
M[t]++;
for (j = M.begin(); j != M.end(); ++j)
cout << j->first << " " << j->second << "\n";
return 0;
}

         注:上面程序總共需要7.6秒處理Bible文檔,其中讀取需要2.4秒,插入需要4.9秒,寫入輸出爲0.3秒。

       爲了減少處理時間,我們採用哈希表的方式,採用一個節點,該節點包含一個指針指向該單詞,一個變量對單詞進行計數,以及一個指針指向下一個節點。


哈希表的結構如下:

typedef struct node*nodeptr;
typedef struct node{
char *word;
int count;
nodeptr next;
} node;
#define NHASH 29989 //定義單詞的最大數
#define MULT 31   //哈希的乘數
nodeptr bin[NHASH];//定義哈希表

接下來將一個單詞或字符串映射到一個無符號的整數,該整數小於NHASH。

 

unsigned inthash(char *p)
unsigned int h = 0;//這裏使用unsignedint是爲了保證爲正數
for ( ; *p; p++)
h = MULT * h + *p
return h % NHASH
 

然後在主函數中,對哈希的每個bin進行賦初值,爲NULL。然後讀取單詞,插入到哈希表中,無序插入。

int main(void)
{for i = [0, NHASH)
bin[i] = NULL
while scanf("%s", buf) != EOF
incword(buf)
for i = [0, NHASH)
for (p = bin[i]; p!= NULL; p = p->next)
print p->word,p->count
return 0
};

插入函數incword如下:

void incword(char*s)
h = hash(s)
for (p = bin[h]; p!= NULL; p = p->next)
if strcmp(s,p->word) == 0
(p->count)++
return
p =malloc(sizeof(hashnode))
p->count = 1
p->word =malloc(strlen(s)+1)
strcpy(p->word,s)
p->next = bin[h]
bin[h] = p
 

         注:使用哈希表的方法需要2.4s的讀,0.5s的插入時間,0.06s的寫入輸出時間。總共需要3s的時間。該方法比C++的STL方法快了一個數量等級。但是使用sets和maps總能保證插入的單詞是有序的,使用hash table則不能保證。Hash table的平均速度非常快,但是對最壞情況不能保證是一顆平衡樹,不支持對單詞的有序操作。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章