【问题标题】:F# take items from a sequenceF# 从序列中获取项目
【发布时间】:2011-08-12 18:55:23
【问题描述】:

我正在努力学习 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);;

【问题讨论】:

    标签: f# sequence take


    【解决方案1】:

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

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

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

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

    4. let result = lines |&gt; Seq.take pos 只接受第一个 pos 项目。您应该跳过这些项目,然后采取pos 项目,如:

    .

    lines
    |> Seq.skip (pos+1)
    |> Seq.take 3
    

    【讨论】:

      【解决方案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     -> ()
      

      【讨论】:

      • 嗨,谢谢--真的应该把那行去掉--可以编辑吗? -- 在我想要获取导致问题的项目的索引之前的行-
      • 刚刚删除它抱歉造成混乱
      • 谢谢 - 使用两个答案的组合 - 希望我可以将两个答案标记为合并和接受:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多