C# 在文本文件中搜索单词并显示其出现的次数



我正在努力如何在Visual Studio,C#中完成我的应用程序... 所有内容都按应有的方式显示,它允许用户打开文本文件并在 listBox 中显示文本文件。 我的应用程序的一部分还有一个文本框和搜索按钮,因此用户能够在文本文件中搜索特定单词,然后有一个 outputLabel,它应该显示单词(文本框中的值(在文本文件中出现的次数。

下面是我的搜索按钮的代码,我不确定从这里开始。

private void searchButton_Click(object sender, EventArgs e)
        {
            int totalAmount;
            totalAmount = AllWords.Count();
        }

如果对您有帮助,她是我应用程序的其余代码(顺便说一下,"使用 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.Match 返回的成功结果。

假设您有一个文本文件和一个单词要在此文本中找到:
(最终后跟一个符号,如.,:)$等(

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();

最新更新