帮我解析一个文本文件并提取特定的值

时间:2011-06-16 10:36:47

标签: f#

我有一个名为lijst.txt的文件。该文件是printmessage eventlog文件的输出。 所有行都具有相同的格式。 我想从每一行中提取用户名,即owned bywas之间的用户名。另外,我想提取页面计数,它位于单词pages printed:.之间。我想将这些值放在一个新的文本文件中。

此致

丹尼斯(F#中的新人)

2 个答案:

答案 0 :(得分: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) )

答案 1 :(得分: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))