【发布时间】: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<string, int>。 -
您尝试过什么?您似乎有两个要添加的新功能;您需要做的不仅仅是让 Stack Overflow 为您编写这些功能。请提供一个很好的minimal reproducible example,展示您尝试过的内容,并准确描述代码的作用以及与您想要的不同之处。