C# 在C语言中为文件中的条目分配数字#
改进的格式 因此,我以前使用的方法都没有帮助我对日志文件数据进行集群:( 现在我要尝试一种索引方法。我需要根据URL字段中出现的关键字为每个日志文件条目编制索引 示例:C# 在C语言中为文件中的条目分配数字#,c#,visual-studio-2008,C#,Visual Studio 2008,改进的格式 因此,我以前使用的方法都没有帮助我对日志文件数据进行集群:( 现在我要尝试一种索引方法。我需要根据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 /r
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/>
192.162.1.4[3/May/2009 00:34:45]“GET/books/casual/4534.pdf”200 454353http://ljdhjg.com“Mozillablahblah”
190.100.1.4[3/May/2009 00:37:45]“GET/resources/help.pdf”200 4353http://ljdhjg.com“Mozillablahblah”
192.162.1.4[3/May/2009 00:40:45]“GET/books/serior/44.pdf”200 234353http://ljdhjg.com“Mozillablahblah”
..我还有数千个这样的条目..现在所有的
“书籍”
都需要分配一个数字…1(比如说)…接下来,“资源”
需要分配2..我如何用C来完成这一点?我的意思是,我知道逻辑。。。
提取关键字..分配编号..将关键字数组与文件的每一行进行比较..如果匹配,则分配.但由于我是C#新手,我真的不知道如何对上述逻辑进行编码.那么..帮助?您可以尝试这种临时分配方法(我假设这意味着在日志项前加上索引) 其中
logEntry
是表示日志文件中每个条目的字符串
对于的日志条目
192.162.1.4[3/May/2009 00:34:45]“GET/books/casual/4534.pdf”200 454353http://ljdhjg.com“Mozillablahblah”
indexedLogEntry
将
1:192.162.1.4[3/May/2009 00:34:45]“GET/books/casual/4534.pdf”200 454353http://ljdhjg.com“Mozillablahblah”
如果使用正则表达式,可能会有一种更优雅的方法。我必须使用开关大小写操作吗?我的意思是,我有大约40个关键字…我为每个关键字提供一个大小写是不现实的,不是吗?你可以使用
哈希表或字典来存储关键字:索引代码>配对。然后使用它构建索引。
/// <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);
}
string indexedLogEntry = GetIndexedEntry(logEntry);