Visual Studio 2008 - 在 C# 中为文件中的条目分配编号
本文关键字:分配 编号 文件 2008 Visual Studio | 更新日期: 2023-09-27 17:55:36
改进了格式
因此,我以前使用的方法都没有帮助我:(对日志文件数据进行聚类
现在我将尝试一种索引方法。为此,我需要根据 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# 中完成此操作?我的意思是,我知道逻辑...
提取关键字..分配编号..将关键字数组与文件的每一行进行比较。如果匹配,则分配。但是由于我是 C# 的新手,我真的不知道如何编写上述逻辑。所以。。帮助?
您可以尝试这种临时方法来分配(我假设这意味着将索引前缀到日志条目),
/// <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
是表示日志文件中每个条目的字符串。
对于logEntry
192.162.1.4 [3/May/2009 00:34:45] "GET /books/casual/4534.pdf" 200 454353 "http://ljdhjg.com" "Mozillablahblah"
indexedLogEntry
将是
1 : 192.162.1.4 [3/May/2009 00:34:45] "GET /books/casual/4534.pdf" 200 454353 "http://ljdhjg.com" "Mozillablahblah"
如果使用正则表达式,则可以使用更优雅的方法。