【问题标题】:C# Search for word in a text file and display the number of times it occursC#在文本文件中搜索单词并显示出现的次数
【发布时间】:2018-04-29 21:55:13
【问题描述】:

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

下面是我的 searchButton 的代码,我不知道从哪里开始。

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

        }

提前谢谢你!

【问题讨论】:

  • 这对初学者来说实际上是非常困难的。 LINQ Count Query 的这一侧或执行您自己的搜索循环,似乎没有真正的方法来获取字符串中任何子字符串的计数。不仅如此,字符串还有一些特殊的怪癖:编码、规范化、大小写。这真的取决于你的最终目标有多高。

标签: c# visual-studio filereader


【解决方案1】:

在文本中查找单词出现次数的一种可能方法是计算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();

【讨论】:

  • @Skylar Rychner 您是否尝试过这些方法。如果他们不适合你,请告诉我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-03
相关资源
最近更新 更多