你可以試試這個即興的方式來分配(我假定這意味着前綴索引的日誌條目),
/// <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"
的indexedLogEntry
的logEntry
將
1 : 192.162.1.4 [3/May/2009 00:34:45] "GET /books/casual/4534.pdf" 200 454353 "http://ljdhjg.com" "Mozillablahblah"
一種更簡潔的方法是可能的,如果一個使用正則表達式。
我是否必須使用開關盒操作?我的意思是,我有約.40個關鍵字......對我來說,爲他們每個人提供一個案件是不切實際的,不是嗎? – wave5459 2011-05-10 03:14:40
您可以使用'HashTable'或'Dictionary'來存儲'keyword':'index'對。然後用它來建立索引。 – 2011-05-10 03:37:08
明白了:)謝謝:) – wave5459 2011-05-10 09:29:05