2011-06-16 92 views
0

我有一个文件叫lijst.txt。该文件是来自printmessage事件日志文件的输出。 所有行都具有相同的格式。 我想从每行中提取用户名,该用户名位于单词owned bywas之间。另外,我想提取位于pages printed:.之间的pagecount。我想将这些值放在一个新的文本文件中。帮我解析一个文本文件并提取具体的值

问候,

丹尼斯(新在F#)

+4

样本输入数据在这里会有很大帮助。 – khachik 2011-06-16 10:39:54

回答

0

我会建议使用正则表达式这一点,是这样的:

open System.Text.RegularExpressions 

let usernameRegex = new Regex(".*owned by\s+(?<username>.*)\s+was.*") 

/// Trys to extract the username from a given line of text. Returns None if the line is malformed 
// Note: You could also use failwith in the else branch or throw an exception or ... 
let extractUsername line = 
    let regexMatch = usernameRegex.Match(line) in 
    if regexMatch.Success then Some regexMatch.Groups.["username"].Value else None 

// In reality you would like to load this from file using File.ReadAllLines 
let sampleLines = 
    ["Some text some text owned by DESIRED USERNAME was some text some text"; 
    "Some text line not containing the pattern"; 
    "Another line owned by ANOTHER USER was"] 

let extractUsernames lines = 
    lines 
    |> Seq.map extractUsername 
    |> Seq.filter (fun usernameOption -> usernameOption.IsSome) 
    |> Seq.map (fun usernameOption -> usernameOption.Value) 

// You can now save the usernames to a file using 
// File.WriteAllLines("FileName", extractUsernames(sampleLines)) 
+0

嗨,thanx为awnser。它的解决方案的一部分,但我想我可以设法排序de用户名并获得每个用户打印的页面(我认为)关心 – Coolzero1974 2011-07-04 07:50:08

0

你可以这样做:

let getBetween (a:string) (b:string) (str:string) = 
     str.Split(a.ToCharArray()).[1].Split(b.ToCharArray()).[0].Trim() 

let total (a:string seq) = 
    (a |> Seq.map Int32.Parse |> Seq.reduce (+)).ToString() 

File.ReadAllLines("inFile") |> Seq.map (fun l -> (getBetween "owned by" "was" l , getBetween "Pages printed:" "." l)) 
|> Seq.groupBy (fun (user,count) -> user) 
|> Seq.map (fun (user,counts) -> user + "\t" + (counts |> Seq.map snd |> total)) 
|> (fun s -> File.WriteAllLines("outFile",s)) 
+0

如何把每个用户的总页数放到一个txt文件中? – Coolzero1974 2011-06-16 19:29:48

+0

我已更新我的答案,请尝试。这将把用户和计数在每一行和用户和计数是由制表符分隔 – Ankur 2011-06-17 04:33:06

+0

嗨,thx的代码,但我得到了很多错误System.formatexeption:inputstring不是在正确的格式 – Coolzero1974 2011-06-17 10:12:53

相关问题