统计文本中每个单词的序列 和 出现次数

本文介绍三种统计文本中单词出现频率的方法:使用STL中的map进行高效统计,利用Hash表实现自定义哈希函数进行单词计数,以及通过构建Trie树进行单词存储与检索。

统计文本中每个单词的序列

使用STL

/*统计文本中出现的单词的序列*/
#include <iostream>
#include <fstream>
#include <string>
#include <set>
using namespace std;
int main()
{
	string str;
	set<string> DistinctWordSet;
	set<string>::iterator it;
	ifstream in("word.txt");
	while(in >> str)
	{
		DistinctWordSet.insert(str);
	}
	//输出
	for (it = DistinctWordSet.begin();it != DistinctWordSet.end();it++)
	{
		cout<<*it<<endl;
	}
	system("pause");
	return 1;
}

统计文本中每个单词的出现次数

STL实现

/*统计文本中每个单词的出现次数*/
#include <iostream>
#include <fstream>
#include <algorithm>
#include <map>
#include <string>
using namespace std;
int main()
{
	string str;
	map<string,int> WordCountMap;
	map<string,int>::iterator it;
	ifstream in("word.txt");//打开文件
	if (in.fail())
	{
		cout<<"打开文件错误!"<<endl;
		exit(0);
	}
	while(in >> str)
	{
		transform(str.begin(),str.end(),str.begin(),::tolower);//大写变小写
		WordCountMap[str]++;
	}
	in.close();
	//输出
	for (it = WordCountMap.begin();it != WordCountMap.end();it++)
	{
		cout<<it->first<<" "<<it->second<<endl;
	}
	system("pause");
	return 1;
}
Hash实现

/*统计文本中每个单词的出现次数*/
#include <iostream>
#include <assert.h>
#include <string>
#include <fstream>
#include <algorithm>
using namespace std;
const int NHASH = 29989;
const int MULT = 31;

class StrNode
{
public:
	string word;
	unsigned int count;
	StrNode* next;
public:
	StrNode(string str) : count(1),next(NULL),word(str){}
};

class CountStr
{
public:
	CountStr();
public:
	unsigned int HashIndex(string str);
	void InsertWord(string str);
	void InitStr(string FileName);
	void Print();
private:
	StrNode* bin[NHASH];
};

CountStr::CountStr()
{
	memset(bin,NULL,NHASH * sizeof(StrNode*));
}

/*如字符串abc的Hash值为(97 *31 + 98)  * 31  + 99*/
unsigned int CountStr::HashIndex(string str)
{
	unsigned int index = 0;
	int strLen = str.size();

	assert(strLen > 0);
	for (int i = 0;i < strLen;i++)
	{
		index = MULT * index + str.at(i);
	}
	return index % NHASH;
}

void CountStr::InsertWord(string str)
{
	StrNode* p = NULL;
	unsigned int index = HashIndex(str);
	for (StrNode* p = bin[index];p != NULL;p = p->next)
	{
		if (str == p->word)
		{
			p->count++;
			return;
		}
	}
	p = new StrNode(str);
	//使用头插法插入节点
	p->next = bin[index];
	bin[index] = p;
}

void CountStr::InitStr(string fileName)
{
	string str;
	ifstream in(fileName.c_str());
	while(in >> str)
	{
		transform(str.begin(),str.end(),str.begin(),::tolower);//大写变小写
		InsertWord(str);
	}
}

void CountStr::Print()
{
	for (int i = 0;i < NHASH;i++)
	{
		for (StrNode* p = bin[i];p;p = p->next)
		{
			cout<<p->word<<" "<<p->count<<endl;
		}
	}
}

int main()
{
	CountStr countStr;
	countStr.InitStr("word.txt");
	countStr.Print();
	system("pause");
	return 1;
}

trie树实现

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <assert.h>
using namespace std;
const int MaxBranchNum = 26;

/*定义trie树结点*/
class TrieNode
{
public:
	char* word;
	int count;
	TrieNode* nextBranch[MaxBranchNum];
public:
	TrieNode() : word(NULL),count(0)
	{
		memset(nextBranch,NULL,sizeof(TrieNode*) * MaxBranchNum);	
	}
};

/*定义类Trie*/
class Trie
{
public:
	Trie();
	~Trie();
	void Insert(const char* str);
	void Print();
private:
	TrieNode* pRoot;
private:
	void Destory(TrieNode* pRoot);
	void Print(TrieNode* pRoot);
};

Trie::Trie()
{
	pRoot = new TrieNode();
}

Trie::~Trie()
{
	Destory(pRoot);
}

/*注意*/
void Trie::Insert(const char* str)
{
	assert(NULL != str);
	int index;
	TrieNode* pLoc = pRoot;
	for (int i = 0;str[i];i++)
	{
		index = str[i] - 'a';//如果区分大小写,可以扩展

		if(index < 0 || index > MaxBranchNum)//不执行插入
		{
			return;
		}

		if (NULL == pLoc->nextBranch[index])
		{
			pLoc->nextBranch[index] = new TrieNode();
		}
		pLoc = pLoc->nextBranch[index];
	}
	if (NULL != pLoc->word)//单词已经出现过
	{
		pLoc->count++;
		return;
	}
	else    //单词没有出现过,应该插入单词
	{
		pLoc->count++;
		pLoc->word = new char[strlen(str) + 1];
		assert(NULL != pLoc->word);
		strcpy(pLoc->word,str);
	}
}

void Trie::Print()
{
	Print(pRoot);
}

/*输出所有的单词*/
void Trie::Print(TrieNode* pRoot)
{
	if (NULL == pRoot)
	{
		return;
	}
	//输出单词
	if (NULL != pRoot->word)
	{
		if (strcmp(pRoot->word,"is") == 0)
		{
			cout<<"is"<<endl;
		}
		if (strcmp(pRoot->word,"it") == 0)
		{
			cout<<"it"<<endl;
		}
		cout<<pRoot->word<<" "<<pRoot->count<<endl;
	}
	//递归处理分支
	for (int i = 0;i < MaxBranchNum;i++)
	{
		Print(pRoot->nextBranch[i]);
	}
}

/*销毁trie树*/
void Trie::Destory(TrieNode* pRoot)
{
	if (NULL == pRoot)
	{
		return;
	}
	for (int i = 0;i < MaxBranchNum;i++)
	{
		Destory(pRoot->nextBranch[i]);
	}
	//销毁单词占得空间
	if (NULL != pRoot->word)
	{
		delete []pRoot->word;   
		pRoot->word = NULL;
	}
	delete pRoot;//销毁结点
	pRoot = NULL;
}


int main(int argc, char *argv[])
{
	string str;
	Trie t;
	ifstream in("word.txt");
	//把单词输入字典树
	while(in >> str)
	{
		transform(str.begin(),str.end(),str.begin(),::tolower);//大写变小写
		//cout<<str<<endl;
		t.Insert(str.c_str());
	}
	//输出
	t.Print();
	system("PAUSE");
	return 1;
}



 

 



<think>好的,我现在需要帮助用户解决如何用C语言编写程序统计文本文件中单词出现次数的问题。首先,我需要回顾用户提供的引用内容,确保回答准确。用户提到的引用[1]、[2]、[3]、[4]都是关于C语言处理文本统计词频的,所以我要整合这些信息。 首先,用户的问题涉及文件读取、字符串处理、单词统计排序输出。我得一步步分解问题。根据引用[3],需要逐行扫描文本,将不同的单词存入数组,在遇到相同单词时增加计数。这可能涉及到如何分割单词,判断是否为有效单词(仅由字母组成),以及大小写转换的问题。 接下来,引用[1]提到要将大写字母转换为小写,所以在处理每个字符时,需要检查是否为字母,将其转为小写。这可能涉及到遍历每个字符,判断是否是字母,如果是,则继续读取直到非字母字符,形成一个单词。 然后,存储这些单词及其出现次数。引用[3]提到使用数组保存单词计数,但当数据量大时,数组的效率可能不高。引用[4]提到了使用树结构或者哈希表,这可能更高效。但用户可能需要一个基础的实现,所以先用数组结构,但需要考虑动态扩容,或者使用链表。不过,用户提供的引用中没有详细说明数据结构的选择,可能需要根据实际情况建议。 另外,引用[2][3]都提到了逐行处理,所以程序需要按行读取文件,然后逐行处理单词。这涉及到文件操作函数,如fopen、fgets等。 接下来,排序输出。用户需要按字典序输出,所以最后需要对所有单词进行排序,可以使用qsort函数,自定义比较函数来实现字符串的比较。 现在,我需要将这些步骤整合成一个算法流程: 1. 读取文件:使用fopen打开文件,检查是否成功。 2. 逐行读取:用fgets读取每一行。 3. 分割单词:对于每一行,逐个字符处理,提取出单词(仅字母组成),转换为小写。 4. 存储单词:将单词存入结构体数组,每个结构体包含单词字符串计数。需要检查是否已存在,存在则计数+1,否则添加新条目。 5. 动态数组管理:可能需要动态分配内存,因为单词数量未知,使用realloc调整数组大小。 6. 排序:使用qsort对结构体数组按单词字典序排序。 7. 输出结果:遍历排序后的数组,打印每个单词及其计数。 在这个过程中需要注意内存管理,避免泄漏。例如,每次添加新单词时,需要为字符串分配内存,在最后释放所有内存。 可能的难点在于如何高效地分割单词存储统计结果。例如,处理连续的非字母字符,或者单词之间的分隔符。例如,遇到字符如逗号、句号、空格等,需要跳过,确认单词的边界。 另外,关于单词的存储结构,用户引用中提到使用数组,但当单词数量很大时,查找是否存在会变得很慢,时间复杂度是O(n)。这时候可以考虑使用更高效的数据结构,比如哈希表或二叉搜索树,如引用[4]提到的树结构。但用户可能希望一个简单实现,所以先用数组,但说明其局限性,可能提到优化的方向。 测试用例需要考虑各种情况,比如大小写混合、带符号的单词、长文本等。 现在,我需要将这些思考整理成一个清晰的步骤说明,给出示例代码框架,同时指出可能的问题优化方法。同时,需要确保代码符合C语言标准,正确使用文件操作字符串处理函数。 最后,生成相关问题,帮助用户进一步学习,比如性能优化、处理特殊字符、使用更高效的数据结构等。</think>### 分步实现文本单词统计程序(C语言) #### 一、核心步骤 1. **文件读取** - 使用`fopen()`打开文件检查是否成功 - 逐行读取内容:`while (fgets(buffer, MAX_LINE, fp) != NULL)` 2. **单词提取** - 定义单词为**仅由字母组成的连续字符序列** - 大小写转换:`tolower()`函数统一为小写 - 示例代码片段: ```c for (int i = 0; buffer[i] != '\0'; i++) { if (isalpha(buffer[i])) { // 判断是否为字母 word[len++] = tolower(buffer[i]); } else if (len > 0) { // 遇到非字母且已有单词内容 word[len] = '\0'; process_word(word); // 处理单词 len = 0; } } ``` 3. **频率统计** - 使用结构体数组存储单词及其计数: ```c typedef struct { char* word; int count; } WordEntry; ``` - 动态扩容策略:初始分配100个元素,每次满时`realloc()`扩大为1.5倍 4. **排序输出** - 使用`qsort()`按字典序排序: ```c int compare(const void* a, const void* b) { return strcmp(((WordEntry*)a)->word, ((WordEntry*)b)->word); } ``` #### 二、完整代码框架 ```c #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> #define MAX_WORD 100 #define INIT_SIZE 100 typedef struct { char* word; int count; } WordEntry; WordEntry* words = NULL; int capacity = 0; int size = 0; void process_word(const char* word) { // 查找是否已存在 for (int i = 0; i < size; i++) { if (strcmp(words[i].word, word) == 0) { words[i].count++; return; } } // 扩容检查 if (size >= capacity) { capacity = capacity ? capacity * 1.5 : INIT_SIZE; words = realloc(words, capacity * sizeof(WordEntry)); } // 添加新单词 words[size].word = strdup(word); words[size].count = 1; size++; } int main() { FILE* fp = fopen("input.txt", "r"); if (!fp) { perror("文件打开失败"); return 1; } char buffer[1024]; while (fgets(buffer, sizeof(buffer), fp)) { char word[MAX_WORD]; int len = 0; for (int i = 0; buffer[i]; i++) { if (isalpha(buffer[i])) { word[len++] = tolower(buffer[i]); } else if (len > 0) { word[len] = '\0'; process_word(word); len = 0; } } // 处理行末未处理的单词 if (len > 0) { word[len] = '\0'; process_word(word); } } // 排序输出 qsort(words, size, sizeof(WordEntry), compare); for (int i = 0; i < size; i++) { printf("%s: %d\n", words[i].word, words[i].count); } // 释放内存 for (int i = 0; i < size; i++) free(words[i].word); free(words); fclose(fp); return 0; } ``` #### 三、关键问题说明 1. **时间复杂度** - 当前实现查找单词采用线性扫描,时间复杂度为$O(n^2)$ - 优化建议:改用哈希表(时间复杂度$O(n)$)或二叉搜索树[^4] 2. **内存管理** - `strdup()`会自动分配内存,需手动`free()` - 注意防止内存泄漏:在程序结束前释放所有动态分配的内存 3. **特殊字符处理** - 当前代码跳过所有非字母字符,如需支持带连字符的单词(如"state-of-the-art"),需修改判断逻辑
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值