F#从序列中提取项目
我正在努力学习F# 我想做的是下载一个网页,把它分成一个序列,然后找到一个项目的索引,并在它之后取下接下来的3个项目 这是密码,有人能告诉我我做错了什么吗F#从序列中提取项目,f#,sequence,take,F#,Sequence,Take,我正在努力学习F# 我想做的是下载一个网页,把它分成一个序列,然后找到一个项目的索引,并在它之后取下接下来的3个项目 这是密码,有人能告诉我我做错了什么吗 let find = "<head>" let page = downloadUrl("http://www.stackoverflow.com") let lines = seq ( page.Replace("\r", System.String.Empty).Split([|"\n"|], StringSplitOpt
let find = "<head>"
let page = downloadUrl("http://www.stackoverflow.com")
let lines = seq ( page.Replace("\r", System.String.Empty).Split([|"\n"|], StringSplitOptions.RemoveEmptyEntries) )
let pos = lines |> Seq.findIndex(fun a -> a == find) // getting a Exception of type 'System.Collections.Generic.KeyNotFoundException' was thrown.
let result = // now to get the next 3 items
printfn "%A" (Seq.toList result);;
let find=“”
let page=下载URL(“http://www.stackoverflow.com")
让lines=seq(page.Replace(“\r”,System.String.Empty)。Split([|“\n”|],StringSplitOptions.RemoveEmptyEntries))
让pos=lines |>Seq.findIndex(fun a->a==find)//引发“System.Collections.Generic.KeyNotFoundException”类型的异常。
让result=//现在获取接下来的3项
printfn“%A”(Seq.toList result);;
此行跳过找到的项目之前的所有内容,而不接受它后面的3个项目
编辑:如果搜索的项目不存在,则Seq.findIndex
失败。您需要序列tryFindIndex
:
match lines |> Seq.tryFindIndex(fun a -> a == find) with
| Some pos -> let result = // now to get the next 3 items
printfn "%A" (Seq.toList result)
| None -> ()
此行跳过找到的项目之前的所有内容,而不接受它后面的3个项目
编辑:如果搜索的项目不存在,则Seq.findIndex
失败。您需要序列tryFindIndex
:
match lines |> Seq.tryFindIndex(fun a -> a == find) with
| Some pos -> let result = // now to get the next 3 items
printfn "%A" (Seq.toList result)
| None -> ()
所以你正在做一些F#文本处理。以下是一些可能的问题:
page.Replace(“\r”,System.String.Empty)。拆分([|“\n”|]
有问题,因为我猜您想拆分项目/单词。此行只拆分行让pos=lines>Seq.findIndex(fun a->a==find)
将=
更改为=
。在F#中,=
是用于比较的布尔运算符let result=lines |>Seq.take pos
只获取第一个pos
项目。您应该跳过这些项目,然后获取pos
项目,如所示:page.Replace(“\r”,System.String.Empty)。拆分([|“\n”|]
有问题,因为我猜您想拆分项目/单词。此行只拆分行让pos=lines>Seq.findIndex(fun a->a==find)
将=
更改为=
。在F#中,=
是用于比较的布尔运算符let result=lines |>Seq.take pos
只获取第一个pos
项目。您应该跳过这些项目,然后获取pos
项目,如所示:您好,谢谢--真的应该删掉那一行--可能会编辑吗?--这是我想获取导致问题的项目索引的前一行--刚刚删除了它--为混淆感到抱歉谢谢--使用两个答案的组合--希望我能将两个答案都标记为合并并接受:)您好,谢谢--真的应该删掉那一行--可能会编辑吗?--这是我想获取导致问题的项目索引的前一行--刚刚删除了它--为混淆感到抱歉谢谢--使用两个答案的组合--希望我能将两个答案都标记为合并并接受:)
lines
|> Seq.skip (pos+1)
|> Seq.take 3