2011-05-10 13 views
0

改進格式在C#中的文件分配號碼條目

所以,沒有我所用以前的方法的幫助我聚集我的日誌文件數據:(

現在我要去嘗試索引方法。 。對於我需要指數基於出現在URL字段中的關鍵詞的每個日誌文件項..

例如:

192.162.1.4 [3/May/2009 00:34:45] "GET /books/casual/4534.pdf" 200 454353 "http://ljdhjg.com" "Mozillablahblah"<br/> 
190.100.1.4 [3/May/2009 00:37:45] "GET /resources/help.pdf" 200 4353 "http://ljdhjg.com" "Mozillablahblah"<br/> 
192.162.1.4 [3/May/2009 00:40:45] "GET /books/serious/44.pdf" 200 234353 "http://ljdhjg.com" "Mozillablahblah"<br/> 

....我有數以千計的更多條目像這樣..

現在所有的"books"都需要分配一個數字...... 1(說)..然後,"resources"需要分配2 ..我如何去完成這個C# ?我的意思是,我知道的邏輯...

提取keyword..assign number..compare關鍵字陣列file..if比賽的每一行分配。但是,由於即時通訊新的C#,我真的不知道如何編碼上述邏輯。 So..help?

回答

0

你可以試試這個即興的方式來分配(我假定這意味着前綴索引的日誌條目),

/// <summary> 
/// Gets the indexed entry. 
/// </summary> 
/// <param name="entry">The log entry.</param> 
/// <returns>The log entry prefixed with the index.</returns> 
private string GetIndexedEntry(string entry) 
{ 
    string keyword = GetKeyword(entry); 

    switch (keyword) 
    { 
     case "books": 
      entry = "1 : " + entry; 
      break; 

     case "resources": 
      entry = "2 : " + entry; 
      break; 
    } 

    // Alternative code (using dictionary) 
    // entry = keywordIndexDictionary[keyword] + " : " + entry; 

    return entry; 
} 

/// <summary> 
/// Gets the keyword. 
/// </summary> 
/// <param name="entry">The log entry.</param> 
/// <returns>The keyword for the specified log entry.</returns> 
private string GetKeyword(string entry) 
{ 
    int index = entry.IndexOf("\"GET"); 
    entry = entry.Substring(index + ("\"GET").Length); 
    index = entry.IndexOf('"'); 
    entry = entry.Substring(0, index).Trim(); 
    return entry.Split('/')[1]; 
} 

// Alternative approach 
/// <summary> 
/// Stores the keyword-index pair 
/// </summary> 
private Dictionary<string, int> keywordIndexDictionary; 

/// <summary> 
/// Builds the dictionary. 
/// </summary> 
private void BuildDictionary() 
{ 
    // Build the dictionary manually 
    // or alternatively read from an settings file and then build the dictionary 
    keywordIndexDictionary.Add("books", 1); 
    keywordIndexDictionary.Add("resources", 2); 
} 

GetIndexedEntry()調用會是什麼樣子,

string indexedLogEntry = GetIndexedEntry(logEntry); 

哪裏logEntry是表示日誌文件中每個條目的字符串。

對於

192.162.1.4 [3/May/2009 00:34:45] "GET /books/casual/4534.pdf" 200 454353 "http://ljdhjg.com" "Mozillablahblah"

indexedLogEntrylogEntry

1 : 192.162.1.4 [3/May/2009 00:34:45] "GET /books/casual/4534.pdf" 200 454353 "http://ljdhjg.com" "Mozillablahblah"

一種更簡潔的方法是可能的,如果一個使用正則表達式。

+0

我是否必須使用開關盒操作?我的意思是,我有約.40個關鍵字......對我來說,爲他們每個人提供一個案件是不切實際的,不是嗎? – wave5459 2011-05-10 03:14:40

+0

您可以使用'HashTable'或'Dictionary'來存儲'keyword':'index'對。然後用它來建立索引。 – 2011-05-10 03:37:08

+0

明白了:)謝謝:) – wave5459 2011-05-10 09:29:05