【问题标题】:I need help displaying a couple of things我需要帮助来展示一些东西
【发布时间】:2015-12-03 06:57:11
【问题描述】:

我正在编写一个搜索输入文本文件(我选择的)的小代码。我正在创建一个搜索功能。到目前为止,我得到它来显示搜索词在文本文件中出现的次数以及行号。我需要帮助才能找到最长的单词并显示它。我还想找到文本文件中最常出现的单词以及显示该单词。

感谢任何帮助、建议或建议。提前谢谢!

这是我的代码:(我还没有编写代码的其他部分。我需要帮助。)

string line;
Console.WriteLine("Enter a word to search for: ");
string userText = Console.ReadLine();
int counter = 0;

string file = "NewTextFile.txt";
StreamReader myFile = new StreamReader(file);

int found = 0;

while ((line = myFile.ReadLine()) != null)
{
    counter++;
    if (line.Contains(userText))
    {
        Console.WriteLine("Found on line number: {0}", counter);
        found++;
    }
}
Console.WriteLine("A total of {0} occurences found", found);

我现在正在尝试使用正则表达式:

        var words = Regex.Matches(File.ReadAllText(file), @"\w+").Cast<Match>()
        .Select((m, pos) => new { Word = m.Value, Pos = pos })
        .GroupBy(s => s.Word, StringComparer.CurrentCultureIgnoreCase)
        .Select(g => new { Word = g.Key, PosInText = g.Select(z => z.Pos).ToList() })
        .ToList();


        foreach (var item in words)
        {
            Console.WriteLine("{0,-15} POS:{1}", item.Word, string.Join(",", item.PosInText));
        }


        for (int i = 0; i < words.Count; i++)
        {
            Console.Write("{0}:{1} ", i, words[i].PosInText.Count);
        } 

【问题讨论】:

  • 当您遍历这些行时,将它们拆分为单词,并跟踪长度最长的那一行。在循环结束时,显示它。对于最常用的单词,您可以为所有单词维护一个Dictionary&lt;string, int&gt;
  • 尝试过什么?您似乎有两个要添加的新功能;您需要做的不仅仅是让 Stack Overflow 为您编写这些功能。请提供一个很好的minimal reproducible example,展示您尝试过的内容,并准确描述代码的作用以及与您想要的不同之处。

标签: c# file io


【解决方案1】:

首先,您需要对文档进行标记,因此请找到某种方法将其拆分为标记。所以定义一个单词有哪些分隔符:空格、逗号、点等。

然后遍历所有标记并将它们存储在Dictionary 中,该Dictionary 将单词映射到它出现的次数。

然后您可以遍历地图并找到出现次数最多的单词和最长的单词。

【讨论】:

    猜你喜欢
    • 2019-05-27
    • 2011-07-21
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    相关资源
    最近更新 更多