1

我正在努力学习 F#

我想做的是下载一个网页,将其拆分为一个序列,然后找到一个项目的索引并在它之后获取接下来的 3 个项目。

这是代码-有人可以告诉我我做错了什么吗?

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);;
4

2 回答 2

3

所以你正在做一些 F# 文本处理。以下是一些可能的问题:

  1. 下载 HTML 页面后,您没有进行任何预处理,例如删除所有 HTML 标记。

  2. page.Replace("\r", System.String.Empty).Split([|"\n"|]是有问题的,因为我猜您想将项目/单词分开。该行仅将行拆分。

  3. let pos = lines |> Seq.findIndex(fun a -> a == find)更改===. 在 F# 中,=是用于比较的布尔运算符。

  4. let result = lines |> Seq.take pos只取第一pos项。您应该跳过这些项目,然后按照以下方式获取pos项目:

.

lines
|> Seq.skip (pos+1)
|> Seq.take 3
于 2011-04-26T06:16:56.317 回答
2
let result = lines |> Seq.take pos

此行跳过找到的项目之前的所有内容,而不是之后的 3 个项目。

编辑: Seq.findIndex如果搜索的项目不存在,则失败。你想要Seq.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     -> ()
于 2011-04-26T06:12:08.010 回答