2012-01-05 27 views
0

我想要統計單詞在文件中出現的次數。是否有捷徑可尋?計算文件中找到單詞的次數

+2

這應該有一個「家庭作業」標籤? – 2012-01-05 02:51:43

+2

哪個部位有問題? (1)讀取文件,(2)將文件拆分爲單詞,(3)統計單詞的出現,(4)打印結果? – 2012-01-05 02:52:12

+2

但你已經知道簡單的方法 - 要求在stackoverflow ;-) – necromancer 2012-01-05 02:54:13

回答

2

如果該文件是一個直接的文本文件,它是在C#中深刻地簡單...

private static int GetWordCount(string fileName, string word) 
{ 
    string content = File.ReadAllText(fileName); 
    string[] words = content.Split(new char[] {'.', '.', ' ', '?', '\n', '\r'}, 
        StringSplitOptions.RemoveEmptyEntries); 
    return words.Count(q => q == word); 
} 

此方法讀取文本字符串,然後分割根據一些分隔符的字符串。然後調用LINQ函數來獲取並重新計數。

+0

我想統計文件中的每個單詞數。你會給我一個解決方案嗎? – Tina 2012-01-06 03:53:36

+0

這很容易做到,但它實際上是一個不同的問題。這個問題與計算一個單詞的出現有關。一個新的問題應該打開一個不同的問題,我現在看到上級已經關閉了這個問題... – 2012-01-06 04:01:11

0
static void Main(string[] args) 
{ 
    StreamReader oReader; 
    if (File.Exists(@"C:\TextFile.txt")) 
    { 
      Console.WriteLine("Enter a word to search"); 
      string cSearforSomething = Console.ReadLine().Trim(); 
      oReader = new StreamReader(@"C:\TextFile.txt"); 
      string cColl = oReader.ReadToEnd(); 
      string cCriteria = @"\b"[email protected]"\b"; 
      System.Text.RegularExpressions.Regex oRegex = new System.Text.RegularExpressions.Regex(cCriteria,RegexOptions.IgnoreCase); 

      int count = oRegex.Matches(cColl).Count; 
      Console.WriteLine(count.ToString()); 
    } 

    Console.ReadLine(); 
} 

OR

的另一種方法。這可能會幫助你更好地理解。

使用集合/泛型概念,我們將輕鬆實現我們的標準。請檢查以下代碼並根據您的場景進行更新。

1)開始閱讀文本文件(使用filestream,進口IO命名空間),

System.IO.StreamReader StreamReader1 = 
new System.IO.StreamReader(Server.MapPath("test.txt")); 

2)追加到字符串生成器。

StringBuilder sbData = new StringBuilder(); 
sbData.Append(StreamReader1.ReadToEnd()); 

3)從StringBuilder(空格,Fullstops,問號,感嘆號,省略號,新線)

string[] arrDataCollection = sbData.ToString().Split(' '); 

4)創建字典SortedList拆分單詞。

​​

5.)循環溢出的數據並獲得不同的集合。

for (int i = 0; i < Words.Length; i++) 
{ 
    slData.Add(i, arrDataCollection[i]); 
} 

6.)獲取不同的單詞,數量和請保存到一個Hashtable

Hashtable htCollections = new Hashtable(); 
foreach (KeyValuePair<int, string> kvp in slData) 
{ 
    table.Add(kvp.Value, kvp.Key); 
} 

7)最後從Hashtable過濾它按照我們的要求,希望這會幫助你。

+0

非常感謝。 – Tina 2012-01-06 06:38:17

+0

但我仍然不知道如何使用創建的哈希表? – Tina 2012-01-06 06:39:08

+0

可能是我沒有完全描述我的問題。例如:string [] str = new string [] {「words」,「values」,「words」,「values」,「Test」,「words」};我想要計算「words」,「值「和」測試「。 – Tina 2012-01-06 06:43:44

相關問題