[英]C# Search for word in a text file and display the number of times it occurs
我正在努力完成如何在Visual Studio,C#中完成我的应用程序的工作。在允许用户打开文本文件并在listBox中显示该文本文件的所有地方,都应按需显示。 我的应用程序部分还具有textBox和searchButton,因此用户可以在文本文件中搜索特定单词,然后有一个outputLabel,应显示单词(文本框内的值)在文本文件中出现了多少次。
以下是我的searchButton的代码,我不确定从这里到哪里。
private void searchButton_Click(object sender, EventArgs e)
{
int totalAmount;
totalAmount = AllWords.Count();
}
如果对您有帮助,对她有帮助,那么她就是我的应用程序代码的其余部分(顺便说一下,“ using System.IO;”也在我的代码中)
namespace P6_File_Reader
{
public partial class ReadingFiles : Form
{
public ReadingFiles()
{
InitializeComponent();
}
List<string> AllWords = new List<string>();
private void openButton_Click(object sender, EventArgs e)
{
OpenFileDialog NewDialogBox = new OpenFileDialog();
// will open open file dialog in the same folder as .exe
NewDialogBox.InitialDirectory = Application.StartupPath;
// filter only .txt files
NewDialogBox.Filter = "Text File | *. txt";
if (NewDialogBox.ShowDialog() == DialogResult.OK)
{
// declare the variables
string Line;
string Title = "", Author = "";
string[] Words;
char[] Delimiters = { ' ', '.', '!', '?', '&', '(', ')',
'-', ',', ':', '"', ';' };
// declare the streamreader variable
StreamReader inputfile;
// to open the file and get the streamreader variable
inputfile = File.OpenText(NewDialogBox.FileName);
// to read the file contents
int count = 0;
while (!inputfile.EndOfStream)
{
//count lines
count++;
// to save the title
Line = inputfile.ReadLine();
if (count == 1) Title = Line;
// to save the author
else if (count == 2) Author = Line;
// else
{
if (Line.Length > 0)
{
Words = Line.Split(Delimiters);
foreach (string word in Words)
if (word.Length > 0) AllWords.Add(word);
}
}
}
// enable searchtextbox AFTER file is opened
this.searchTextBox.Enabled = true;
searchTextBox.Focus();
// close the file
inputfile.Close();
// to display the title & author
titleText.Text = Title + Author;
totalAmount.Text = AllWords.Count.ToString("n3");
wordsListBox.Items.Clear();
int i = 0;
while (i < 500)
{
wordsListBox.Items.Add(AllWords[i]);
i++;
}
}
}
private void DisplayList(List<string> wordsListBox)
{
foreach (string str in wordsListBox)
{
MessageBox.Show(str);
}
}
先感谢您!
查找文本中单词出现的次数的一种可能方法是对Regex.Matches返回的成功结果进行计数 。
假设您有一个文本文件和一个可在此文本内找到的单词:
(最终后跟.,:)$
等符号.,:)$
。
string text = new StreamReader(@"[SomePath]").ReadToEnd();
string word = "[SomeWord]" + @"(?:$|\W)";
这将返回匹配数:
int WordCount = Regex.Matches(text, word).Cast<Match>().Count();
这将为您提供在文本内找到这些单词的索引位置:
List<int> IndexList = Regex.Matches(text, word).Cast<Match>().Select(s => s.Index).ToList();
要执行不区分大小写的搜索,请包含RegexOptions.IgnoreCase
。
Regex.Matches(text, word, RegexOptions.IgnoreCase)
如果此操作(某种程度的通用性)不足以获取所需的结果,请优化搜索方式。
您可以使用以下方法检查结果,创建匹配列表:
List<string> ListOfWords = Regex.Matches(text, word, RegexOptions.IgnoreCase)
.Cast<Match>()
.Select(s => s.Value)
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.