gpt4 book ai didi

f# - FParsec:如何在 fparsec 中解析日期(新手)

转载 作者:行者123 更新时间:2023-12-04 20:00:40 24 4
gpt4 key购买 nike

我正在使用 Bill Casarin关于如何使用 fparsec 解析分隔文件的帖子,我正在简化逻辑以了解代码的工作原理。我正在将多行分隔文档解析为 Cell 列表结构(目前),其中 Cell 是字符串或 float 。在这方面我完全是个新手。

我在解析 float 时遇到问题 - 在典型情况下(由制表符分隔的单元格,包含数字)它可以工作。然而,当一个单元格恰好是以数字开头的字符串时 - 它会分崩离析。

我如何修改 pFloatCell 以解析(尽管通过选项卡的方式)为 float 或什么都不解析?

谢谢

type Cell = 
| String of string
| Float of float
.
.
.
let pStringCell delim =
manyChars (nonQuotedCellChar delim)
|>> String

// this is my issue. pfloat parses the string one
// char at a time, and once it starts off with a number
// it is down that path, and errors out
let pFloatCell delim =
FParsec.CharParsers.pfloat
|>> Float

let pCell delim =
(pFloatCell delim) <|> (pStringCell delim)
.
.
.
let ParseTab s =
let delim = "\t"
let res = run (csv delim) s in
match res with
| Success (rows, _, _) -> { IsSuccess = true; ErrorMsg = "Ok"; Result = stripEmpty rows }
| Failure (s, _, _) -> { IsSuccess = false; ErrorMsg = s; Result = [[]] }
.
.
.
let test() =

let parsed = ParseTab data

哎呀,我昨晚迟到了。我的意思是发布数据。第一个有效

let data = 
"s10 Mar 2011 18:28:11 GMT\n"

虽然这会返回一个错误:

let data = 
"10 Mar 2011 18:28:11 GMT\n"

返回,无论是否有 ChaosP 的推荐:

ErrorMsg = "Error in Ln: 1 Col: 3\r\n10 Mar 2011 18:28:11 GMT\r\n ^\r\nExpecting: end of file, newline or '\t'\r\n"

看起来尝试工作正常。在第二种情况下,它只抓取到 10 - 并且 pfloat 的代码只查找第一个空格。我需要说服 pfloat 它需要一直查找到下一个制表符或换行符,而不管它之前是否有空格;通过执行 Double.Parse 编写我自己的 pfloat 版本 - 但我宁愿依赖库。

最佳答案

由于您要解析的文本看起来有点不明确,因此您需要修改您的 pCell 解析器。

let sep delim =
skipString delim <|> skipAnyOf "\r\n" <|> eof

let pCell delim =
attempt (pFloatCell delim .>> sep delim) <|> (pStringCell delim .>> sep delim)

这也意味着您需要修改使用 pCell 的解析器。

let pCells delim =
many pCell delim

注意

.>> 运算符实际上非常简单。把它想象成蛙跳运算符。应用右侧并忽略结果后返回左侧的值。

Parser<'a, 'b> -> Parser<'c, 'b> -> Parser<'a, 'b>

关于f# - FParsec:如何在 fparsec 中解析日期(新手),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5630012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com