2011-12-19 28 views
0

我有一個文本文件,其中包含多行,其中許多行重複。按等級順序顯示文本文件中的行

我想描述一個列表,其中出現最多的出現在頂部和最底部。

但是,我想要顯示字符串出現在列表中的次數。

我該怎麼做呢?

回答

0

快速「N」簡單的方法是使用一個Dictionary和循環:

using(StreamReader sr = new StreamReader("my file")) { 
    Dictionary<string, int> items = new Dictionary<string, int>(); 

    while(sr.BaseStream.Position < sr.BaseStream.Length) { 
     string s = sr.ReadLine(); 
     if(items.ContainsKey(s)) { 
      items[s]++; 
     } else { 
      items.Add(s, 1); 
     } 
    } 

    // You now have a dictionary of unique strings and their counts - you can sort it however you need. 
} 
0

如果文件不是太大,也就是說,如果它可以存放在內存中,您可以將其存儲在一本字典。

做「文字線」的字典 - >

讀取文件中的行同時「的,它已經看到的次數」。如果該行已經在字典中,則將字典值加1。如果該行是新行,請將其添加到字典中並將值設置爲1。

讀取完整個文件後,可以取出鍵/值。按值排序以查找最常出現的值並打印結果。

0

爲.NET框架3.0的代碼:

using System; 
using System.IO; 
using System.Collections.Generic; 

public class Program 
{ 
    private static int Compare(KeyValuePair<string, int> kv1, KeyValuePair<string, int> kv2) 
    { 
    return kv2.Value == kv1.Value ? kv1.Key.CompareTo(kv2.Key) : kv2.Value - kv1.Value; 
    } 

    public static void Main() 
    { 
    Dictionary<string, int> histogram = new Dictionary<string, int>(); 
    using (StreamReader reader = new StreamReader("Test.txt")) 
    { 
     string line; 
     while ((line = reader.ReadLine()) != null) 
     { 
     if (histogram.ContainsKey(line)) 
      ++histogram[line]; 
     else 
      histogram.Add(line, 1); 
     } 
    } 

    List<KeyValuePair<string, int>> sortedHistogram = new List<KeyValuePair<string, int>>(histogram); 
    sortedHistogram.Sort(Compare); 
    foreach (KeyValuePair<string, int> kv in sortedHistogram) 
     Console.WriteLine("{0}\t{1}", kv.Value, kv.Key); 
    } 
} 

的Test.txt:

ddd 
aaa 
ccc 
bbb 
aaa 
aaa 
bbb 

輸出:

3 aaa 
2 bbb 
1 ccc 
1 ddd 
+0

我不能用這個 - 框架4.0? – qwertyuywertwer 2011-12-19 00:49:02

+0

是的 - 對不起,我修正了這個:)請現在測試它 – kol 2011-12-19 00:54:20

+0

我不得不刪除LINQ部分,它出現在.NET 3.5中 – kol 2011-12-19 00:59:18