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

时间:2018-04-29 21:55:14

标签: c# visual-studio filereader

我正在努力研究如何在Visual Studio中完成我的应用程序,C#... 应该允许用户打开文本文件并在listBox中显示文本文件的所有单词。 我的应用程序的一部分还有一个textBox和searchButton,因此用户可以在文本文件中搜索特定的单词,然后有一个outputLabel,它应该显示文本文件中单词(textBox中的值)出现的次数

以下是我的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);
            }

        }

提前谢谢!

1 个答案:

答案 0 :(得分:0)

查找文本中单词出现次数的一种可能方法是计算Regex.Matches返回的成功结果。

假设您有一个文本文件和一个要在此文本中找到的单词:
(最后跟着像GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest( myBucket, myKey, HttpMethod.PUT) .withSSEAlgorithm(SSEAlgorithm.KMS.getAlgorithm()); request.setExpiration(new DateTime().plusMinutes(30).toDate()); request.setContentType("image/jpeg"); URL puturl = s3.generatePresignedUrl(request); 等符号)

.,:)$

这将返回匹配数:

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)