2015-12-03 82 views
1

我正在研究一個小代碼,用於搜索輸入文本文件(我的選擇)。我正在創建一個搜索功能。到目前爲止,我得到它顯示搜索詞在文本文件中出現多少次以及行號。我需要幫助找到最長的單詞並顯示它。另外我想找到文本文件中最常出現的單詞以及顯示單詞。我需要幫助顯示幾件事

讚賞任何幫助,建議或建議。先謝謝你!

這裏是我的代碼:(我沒有寫代碼的另一部分,我需要它的幫助。)

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

在遍歷行時,將它們拆分爲單詞,跟蹤最長的單詞。在循環結束時,顯示它。對於最常見的單詞,您可以爲所有單詞保留一個「字典」。 –

+0

你有什麼_tried_?你似乎有兩個你想添加的新功能;您需要做的不僅僅是要求Stack Overflow爲您編寫這些功能。請提供一個很好的[mcve]顯示你已經嘗試過的內容,並精確地描述代碼的作用,以及與你想要的不同之處。 –

回答

0

首先你需要標記你的文檔,所以找一些方法將它分成標記。因此,請定義一個單詞的分隔符:空格,逗號,點等。

然後遍歷所有標記並將它們存儲在Dictionary中,該標記將單詞映射到它出現的次數。

然後,您可以遍歷地圖,找到最多和最長的單詞。