在文本文件中搜索






1.43/5 (8投票s)
这个程序用于在文本文件中搜索单词。
引言
这是一个我的项目,包含一个在文本文件中搜索的程序。假设你有一组文本文件存储在硬盘的某个位置。你想找到一些文本文件,但你不记得文件名了。但是,你知道你正在寻找的内容,因此你有一些关键词可以搜索。这就像 Windows 的搜索功能。
背景
一些要求是:
- 创建
FileList
:创建一个名为FileList
的文本文件,用于存储所有文本文件的路径。该文件的每一行都是一个文件路径。每行都有一个 ID 来标识文件路径。ID 编号从 0 开始。 - 索引:扫描所有文本文件,并将每个单词存储到二叉搜索树中,以便快速搜索。树中的每个节点包含一个单词、一个 ID 编号列表以及左右指针。
- 显示:仅输出包含关键词的文本文件的一小部分内容以及 ID,以便知道搜索了哪个文件。
Using the Code
为了创建 FileList
,我使用 CStdioFile
类。
// Create file
CStdioFile file;
file.Open("FileList.txt",CFile::modeCreate|CFile::modeReadWrite);
CFileFind Finder; // Find file path
BOOL bWorking = Finder.FindFile(m_PATH + "\\*.txt"); // Only file text files
while(bWorking)
{
bWorking = Finder.FindNextFile();
if (!Finder.IsDirectory())
{
file.WriteString(Finder.GetFilePath()); // Write file path
file.WriteString("\n");
}
}
file.Close();
为了搜索,我使用二叉搜索树来存储单词。首先,我扫描存储文本文件的目录以创建 FileList
。然后,打开 FileList
中的每个文本文件以扫描单词。每个单词都存储在 BST 中。一个单词可以有多个 ID,所以我使用线性链表来存储 ID 编号。
// Search word
ListID* CTinyGoogleDlg::SearchWord(string key)
{
tree* current;
ListID *tmp = NULL;
// Find word
if (head)
{
current = head;
while (current)
{
if (strcmp(current->word,key) == 0)
break;
else
if (strcmp(current->word,key) < 0)
current = current->right;
else
if (strcmp(current->word,key) > 0)
current = current->left;
}
}
else
MessageBox("Something's wrong!");
// Return list of IDs
if (!current)
return tmp;
else
return current->IDs;
}
然后,要求用户输入要搜索的关键词。在二叉树中搜索以查找关键词是否存在。如果存在,则使用 ID 打开文本文件。然后,在结果中打印出文本文件的一些行。
// Display results
int CTinyGoogleDlg::Display(ListID *curr)
{
CStdioFile file;
CString sText;
m_RESULT = "";
if (curr)
{
if (file.Open("FileList.TXT",CFile::modeRead))
{
int count = -1;
while (curr)
{
// Find file path to open text file by checking ID
CString path;
do
{
file.ReadString(path);
count += 1;
}while(count < curr->ID);
CString DocID;
DocID.Format("%d",curr->ID);
m_RESULT = m_RESULT + "\r\nDocID:" + DocID + "\r\n";
// Open file and display a part of paragraph
CStdioFile read;
read.Open(path,CFile::modeRead);
for (short nLineCount = 0; nLineCount < 16; nLineCount++)
{
read.ReadString(sText);
m_RESULT = m_RESULT + sText + "\r\n";
}
// Set lines in edit
GetDlgItem(IDC_EDIT_RESULT)->SetWindowText(m_RESULT);
read.Close();
curr = curr->next;
}
}
file.Close();
}
else
MessageBox("NOT FOUND!");
return 0;
}
关注点
最初,我在如何查找文件路径上遇到了一些麻烦。这并不非常困难,但在我这个水平上,并不容易。但是,我在互联网上找到了一些方法,CodeProject 帮助了我很多。现在,我将我的小程序与其他人分享。
历史
这个程序的第一个版本是作为 Win32 控制台应用程序编写的。这个版本是一个 MFC 应用程序。