找回密码
 立即注册→加入我们

QQ登录

只需一步,快速开始

搜索
热搜: 下载 VB C 实现 编写
查看: 3553|回复: 1

【C】语言写的基于Trie的字典统计单词出现次数

[复制链接]

17

主题

41

回帖

770

积分

用户组: 大·技术宅

UID
6266
精华
6
威望
58 点
宅币
516 个
贡献
50 次
宅之契约
0 份
在线时间
41 小时
注册时间
2020-9-26
发表于 2020-10-23 21:46:02 | 显示全部楼层 |阅读模式

欢迎访问技术宅的结界,请注册或者登录吧。

您需要 登录 才可以下载或查看,没有账号?立即注册→加入我们

×
本帖最后由 new_starter 于 2020-11-2 23:11 编辑

受到:【C】语言编写的字典支持各种类型扩展 这篇帖子的启发,写了一个C语言基于Trie的字典。
这个工程使用了StoneValley库。
StoneValley库在使用的时候将库文件全部添加到工程即可。
以后还会写一些基于StoneValley库的代码供大家参考。
以下是主函数文件的代码:

  1. #include <stdio.h>
  2. #include <ctype.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include "svtree.h"
  6. #include "svstring.h"

  7. typedef struct st_VOCABULARY
  8. {
  9.         long freq; /* 单词频率 */
  10.         char * pword; /* malloc申请的单词字符串 */
  11. } VOCABULARY, * P_VOCABULARY;

  12. P_VOCABULARY CreateWord()
  13. {
  14.         P_VOCABULARY pvol = malloc(sizeof(VOCABULARY));
  15.         if (NULL != pvol)
  16.         {
  17.                 pvol->freq = 1;
  18.                 pvol->pword = NULL;
  19.         }
  20.         return pvol;
  21. }

  22. void DeleteWord(P_VOCABULARY pvol)
  23. {
  24.         free(pvol->pword);
  25.         free(pvol);
  26. }

  27. void DestoryArray(P_ARRAY_Z parrz)
  28. {
  29.         size_t i = 0;
  30.         for (; i < parrz->num; ++i)
  31.         {
  32.                 P_VOCABULARY pvol = *(((P_VOCABULARY *)parrz->pdata) + i);
  33.                 DeleteWord(pvol);
  34.         }
  35.         strFreeArrayZ(parrz);
  36. }

  37. int CbfPrintResult(void * pitem, size_t param)
  38. {
  39.         printf("%s %lu\n", (*((P_VOCABULARY *)pitem))->pword, (*((P_VOCABULARY *)pitem))->freq);
  40.         DWC4100(param);
  41.         return CBF_CONTINUE;
  42. }

  43. int cbfcmpchar(const void * px, const void * py)
  44. {
  45.         return *(char *)px - *(char *)py;
  46. }

  47. int cbfcmpfreq(const void * px, const void * py)
  48. {
  49.         return (*(P_VOCABULARY *)py)->freq - (*(P_VOCABULARY *)px)->freq;
  50. }

  51. int main(int argc, char * argv[])
  52. {
  53.         int c;
  54.         long i, j = 0, k = 0, sizeBuffer = 1024, sizeArray = 1024;
  55.         BOOL bCase = FALSE, bSort = FALSE;
  56.         char * buffer = NULL;
  57.         P_TRIE_A ptrie;
  58.         ARRAY_Z arrz;

  59.         if (NULL == (buffer = (char *) malloc(sizeBuffer)))
  60.                 return 1;
  61.         *buffer = '\0';
  62.         if (NULL == (ptrie = treCreateTrieA()))
  63.                 return 2;
  64.         if (NULL == strInitArrayZ(&arrz, sizeArray, sizeof(P_VOCABULARY)))
  65.                 return 3;

  66.         for (i = 1; i < argc; ++i)
  67.         {
  68.                 if (0 == strcmp("-s", argv[i])) /* 排序开关 */
  69.                         bSort = TRUE;
  70.                 else if (0 == strcmp("-c", argv[i])) /* 大小写开关 */
  71.                         bCase = TRUE;
  72.                 else
  73.                         return 4;
  74.         }
  75.         while (EOF != (c = fgetc(stdin)))
  76.         {
  77.                 if (j >= sizeBuffer)
  78.                 {
  79.                         char * tempBuffer;
  80.                         sizeBuffer += 1024;
  81.                         if (NULL == (tempBuffer = realloc(buffer, sizeBuffer)))
  82.                                 return 5;
  83.                         buffer = tempBuffer;
  84.                 }
  85.                 if (c >= 'A' && c <= 'Z')
  86.                 {
  87.                         *(buffer + j++) = bCase ? (char)c : (char)tolower(c);
  88.                 }
  89.                 else if (c >= 'a' && c <= 'z')
  90.                 {
  91.                         *(buffer + j++) = (char)c;
  92.                 }
  93.                 else
  94.                 {
  95.                         *(buffer + j) = '\0';
  96.                         if (0 != j)
  97.                         {
  98.                                 size_t * presult;
  99.                                 P_VOCABULARY pvol;
  100.                                 size_t bufferLen = strlen(buffer);
  101.                                 /* 在Trie里查询buffer所包含的单词 */
  102.                                 if (NULL == (presult = treSearchTrieA(ptrie, buffer, bufferLen, sizeof(char), cbfcmpchar)))
  103.                                 {
  104.                                         if (k >= sizeArray)
  105.                                         {
  106.                                                 sizeArray += 1024;
  107.                                                 strResizeArrayZ(&arrz, sizeArray, sizeof(P_VOCABULARY));
  108.                                         }
  109.                                         /* 如果没找到就创建一个新单词 */
  110.                                         pvol = CreateWord();
  111.                                         /* 将新单词插入Trie */
  112.                                         treInsertTrieA(ptrie, buffer, bufferLen, sizeof(char), (size_t)pvol, cbfcmpchar);
  113.                                         if (NULL == (pvol->pword = malloc(bufferLen + 1)))
  114.                                                 return 6;
  115.                                         memcpy(pvol->pword, buffer, bufferLen + 1);
  116.                                         /* 将新单词的指针存储在数组里 */
  117.                                         *(((P_VOCABULARY *)arrz.pdata) + k++) = pvol;
  118.                                 }
  119.                                 else
  120.                                 {        /* 如果找到单词,就把Trie里存储的Appendix拿出来转换为P_VOCABULARY指针,并且把频率+1 */
  121.                                         pvol = (P_VOCABULARY)*presult;
  122.                                         ++pvol->freq;
  123.                                 }
  124.                         }
  125.                         j = 0;

  126.                 }
  127.         }
  128.         strResizeArrayZ(&arrz, k, sizeof(P_VOCABULARY));
  129.         if (bSort)
  130.                 strSortArrayZ(&arrz, sizeof(P_VOCABULARY), cbfcmpfreq);
  131.         strTraverseArrayZ(&arrz, sizeof(P_VOCABULARY), CbfPrintResult, 0, FALSE);
  132.         DestoryArray(&arrz);
  133.         treDeleteTrieA(ptrie, sizeof(char));
  134.         free(buffer);
  135.         return 0;
  136. }
复制代码

使用的时候(在Linux环境下)将工程里所有的文件编译为一个名为freq的可执行体:
$ cc *.c -o freq
将可执行体移动到Debug文件夹下就可以对其测试:
$ mv freq ../Debug
以下是一个供测试的小短文:
A wildfire burning in Grand County, Colorado, has exploded from 19,000 acres to more than 125,000 on Thursday, forcing thousands of families to evacuate.
The so-called East Troublesome Fire raced through the town of Grand Lake and into the western portion of Rocky Mountain National Park, which closed to visitors Thursday, CBS Denver reported.
Thick smoke and flames were closing in on homes and terrifying residents. Security video even captured the scene as flames overtook a home. It was not immediately clear how much damage the fire caused in the Grand Lake community.
"We know that historic buildings and businesses are on people's minds, and we just don't have confirmed information at this time. Many of the buildings and the establishments, they are the heart and soul of our community. And as soon we know something definitive, we'll share with those who are affected and the community," Mayor Steve Kudron said late Thursday morning, according to the TV station.
The flames are being driven by high winds and dead, dry timber.
"We plan for the worst. This is the worst of the worst of the worst," said Grand County Sheriff Brett Schroetlin while referencing the fire's 100,000-acre jump in mere hours.
Nearly 300 firefighters are battling the flames in dense wooded hills as the fire continues to spread into the national park. This wildfire could end up merging with the Cameron Peak Fire, which was reported to be burning just a few miles away, according to CBS Denver.
因为程序是用stdin作为输入,所以使用管道连接程序十分方便:
输入以下代码按单词出现顺序统计单词出现频率(区分大小写):
$ cat new2.txt | ./freq -c
A 1
wildfire 2
burning 2
in 5
Grand 4
County 2
Colorado 1
has 1
exploded 1
from 1
acres 1
to 7
more 1
than 1
on 3
Thursday 3
forcing 1
thousands 1
of 7
families 1
evacuate 1
The 2
so 1
called 1
East 1
Troublesome 1
Fire 2
raced 1
through 1
the 19
town 1
Lake 2
and 9
into 2
western 1
portion 1
Rocky 1
Mountain 1
National 1
Park 1
which 2
closed 1
visitors 1
CBS 2
Denver 2
reported 2
Thick 1
smoke 1
flames 4
were 1
closing 1
homes 1
terrifying 1
residents 1
Security 1
video 1
even 1
captured 1
scene 1
as 3
overtook 1
a 2
home 1
It 1
was 2
not 1
immediately 1
clear 1
how 1
much 1
damage 1
fire 3
caused 1
community 3
We 2
know 2
that 1
historic 1
buildings 2
businesses 1
are 5
people 1
s 2
minds 1
we 3
just 2
don 1
t 1
have 1
confirmed 1
information 1
at 1
this 1
time 1
Many 1
establishments 1
they 1
heart 1
soul 1
our 1
And 1
soon 1
something 1
definitive 1
ll 1
share 1
with 2
those 1
who 1
affected 1
Mayor 1
Steve 1
Kudron 1
said 2
late 1
morning 1
according 2
TV 1
station 1
being 1
driven 1
by 1
high 1
winds 1
dead 1
dry 1
timber 1
plan 1
for 1
worst 4
This 2
is 1
Sheriff 1
Brett 1
Schroetlin 1
while 1
referencing 1
acre 1
jump 1
mere 1
hours 1
Nearly 1
firefighters 1
battling 1
dense 1
wooded 1
hills 1
continues 1
spread 1
national 1
park 1
could 1
end 1
up 1
merging 1
Cameron 1
Peak 1
be 1
few 1
miles 1
away 1

输入以下代码可以按频率由高到低的顺序显示单词和出现次数:
$ cat new2.txt | ./freq -s -c
以下代码可以显示包含特定字符串“the”的单词及出现次数(不区分大小写):
$ cat new2.txt | ./freq | grep "the"

这里放出打包好的工程源码:
freq.7z (67.52 KB, 下载次数: 1)

本帖被以下淘专辑推荐:

回复

使用道具 举报

QQ|Archiver|小黑屋|技术宅的结界 ( 滇ICP备16008837号 )|网站地图

GMT+8, 2024-4-16 23:09 , Processed in 0.037566 second(s), 35 queries , Gzip On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表