2013-02-23 18 views
-1

我有一個文件閱讀從文件獨特的元素在C#

outlook temperature Humidity Windy PlayTennis 

sunny  hot  high  false N 

sunny  hot  high  true N 

overcast hot  high  false P 

rain  mild  high  false P 

rain  cool  normal false P 

我想讀從每列僅獨特的元素。

我的輸出中應該是:

elements: occurence   
sunny : 2 
overcast :1 
rain : 2 
hot: 3 
cold : ans so on 
mild 
high 
normal 
true 
false 
N 
P 

我想要的,存儲在這個詞典中鍵值對 關鍵將是我行元素。值將是它的列元素。 請幫忙。

+0

文件中的分隔符是什麼?什麼是字典,一個'Dictionary '?什麼是行列,你的意思是行嗎? – 2013-02-23 19:18:46

+0

空間是分隔符.. – 2013-02-23 19:23:58

+0

詞典 2013-02-23 19:24:15

回答

0

歐凱,所以首先你要加載的文件內容:

string[] allLines = File.ReadAllLines(filePath); 

現在,你應該刪除空行並用單個空格字符替換多個空格。正則表達式和Linq在這裏派上用場。

string[] nonEmptyLines = allLines.Where(s => s.Trim(' ') != "") 
       .Select(s => Regex.Replace(s, @"\s+", " ")).ToArray(); 

現在,讓我們讀列標題:

string[] columnHeaders = null; 
if (nonEmptyLines.Length > 0) 
    columnHeaders = nonEmptyLines[0].Split(); 
else 
    return; 

檢查多少列有:

int columnsCount = columnHeaders.Length; 

跳過包含列標題的第一行,並分割值字符串數組以下Linq語法。

var linesValues = nonEmptyLines.Skip(1).Select(l => l.Split()); 

最後,它的時間來寫詞典獨特的結果:

Dictionary<string, string> columnValues = new Dictionary<string, string>(); 
for (int i = 0; i < columnsCount; i++) 
{ 
    foreach (string[] values in linesValues) 
    { 
     if (!columnValues.ContainsKey(values[i])) 
     { 
      columnValues.Add(values[i], columnHeaders[i]); 
     } 
    } 
} 

這就是全部。我已經在您的示例中對其進行了測試,並且對我有用。

+0

heyy那爲我工作...這是偉大的 – 2013-02-24 00:47:12

+0

我也想找到每件事情的發生..即陽光應該是2..overcast應該是1..hot應該是3 .. 我嘗試過,但我得到所有字母的發生。 可以請你幫忙 – 2013-02-25 19:31:19

0

只需爲每列創建一個HashSet並將其存儲在相應的HashSet中。完成將所有元素添加到HashSet後,打印每個HashSet中的所有元素。

var text1 = File.ReadAllLines(file); 
HashSet<string>[] columns = new HashSet<string>[text1[0].Split(" \t".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Length]; 

for(int i=0; i<columns.Length; i++) 
{ 
    columns[i] = new HashSet<string>(); 
} 

foreach (string row in text1.Skip(1)) 
{ 
    string[] words = row.Split(" \t".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); 
    if (words.Length == columns.Length) 
    { 
     for (int i = 0; i < words.Length; i++) 
     { 
      columns[i].Add(words[i]); 
     } 
    } 
} 

for (int i = 0; i < columns.Length; i++) 
{ 
    foreach (string value in columns[i]) 
    { 
     Console.WriteLine(value); 
    } 
} 
+0

它的工作完美... 謝謝你vv .. – 2013-02-24 00:46:30

+0

我也想找到每件事的發生..即陽光應該是2..overcast應該是1..hot應該是3 ..我試過但我得到所有字母的出現。你可以請幫助 – 2013-02-25 19:31:41