现在的位置: 首页 > 综合 > 正文

统计目录下所有文章单词数量

2013年12月06日 ⁄ 综合 ⁄ 共 2146字 ⁄ 字号 评论关闭

以前写的一个程序,大概是考研的时候写的

当时也是一时兴起

主要功能为选取某一目录,然后对目录下所有特定扩展名的文本文件进行扫描,统计所有单词数量

最后按从多到少统计到一个txt里。

基于WTL写的

关键代码如下

int CMainFrame::WordCensus()
{
	WIN32_FIND_DATA FileData; 
	HANDLE hSearch;
	BOOL fFinished = FALSE; 
	TCHAR szPath[MAX_PATH];

	lstrcat(m_szPathName, TEXT("\\"));

	lstrcpy(szPath, m_szPathName);
	lstrcat(szPath, TEXT("*.lrc"));
	m_view.m_bStart = true;
	//m_view.OnPaint();
	lstrcpy(m_view.m_szFileName, szPath);
	hSearch = FindFirstFile(szPath, &FileData); 
	if (hSearch == INVALID_HANDLE_VALUE) 
	{ 
		::MessageBox(NULL, "Search Failed!", 
			"error.", MB_ICONERROR); 
		return -1;
	}
	while (!fFinished) 
	{ 
		lstrcpy(szPath, m_szPathName);
		lstrcat(szPath, FileData.cFileName);
		//RECT rect;
		//GetClientRect(&rect);
		//TextOut(m_hdc, rect.right/2, rect.bottom/2, szPath, lstrlen(szPath));
		//lstrcpy(m_view.m_szFileName, szPath);
		
		HandleFile(szPath);
		if (!FindNextFile(hSearch, &FileData)) 
		{
			if (GetLastError() == ERROR_NO_MORE_FILES) 
			{ 
				::MessageBox(NULL, "Succss.", 
					"Search completed.", MB_OK); 
				fFinished = TRUE; 
				//m_view.m_bStart = false;
			} 
			else 
			{ 
				return -1; 
			} 
		}

	}
	if (!FindClose(hSearch)) 
	{ 
		return -1; 
	} 

	lstrcpy(szPath, m_szPathName);
	lstrcat(szPath, TEXT("result.txt"));
	ofstream outfile(szPath);
	if(!outfile.is_open())
	{
		::MessageBox(NULL, "Cannot open the result.txt!", 
			"error.", MB_ICONERROR); 
		return -1;
	}

	vector<PAIR> vec;
	map<string, int>::const_iterator it = m_wordcount.begin();
	for(; it != m_wordcount.end(); it++)
	{
		vec.push_back(make_pair(it->first, it->second));
	}
	sort(vec.begin(), vec.end(),cmp);
	vector<PAIR>::iterator iter = vec.begin();
	while(iter != vec.end())
	{
		outfile << (*iter).first << "-------------" << (*iter).second << endl;
		++iter;
	}

	return 0;
}

int CMainFrame::HandleFile(LPCTSTR lpFileName)
{
	ifstream inFile(lpFileName);
	if(!inFile)
		return -1;
	string s;
	string word;
	istringstream isstream;
	while(getline(inFile, s))
	{
		isstream.str(s);
		while(isstream >> word)
		{
			if(word[0] == '[')
				continue;
			if(!isalpha(word[word.size()-1]))
				word.resize(word.size()-1);
			for(string::size_type index = 0; index != word.size(); ++index)
			{
				word[index] = tolower(word[index]);
			}
			++m_wordcount[word];
		}
		isstream.clear();
	}
	inFile.close();
	return 0;
}

当时写这个程序主要还是因为发现STL中容器很好使,就写了这个程序练练手

好像是晚上10点的时候最终写成的,当时还发到寝室群里

以前写代码,真是几乎不写注释啊

现在一般不这样了

一点说明:

if(word[0] == '[')

主要是因为当时用于处理新概念课文的字幕,所以去掉了每行开头的时间说明

最关键的数据结构是一个map,定义如下:

map<string, int> m_wordcount;

即每个单词的出现次数

另外,用C++的流来解析单词,而不是自己写函数

【上篇】
【下篇】

抱歉!评论已关闭.