gpt4 book ai didi

c# - 如何使用 Sprache 解析可以以任何顺序出现的行?

转载 作者:行者123 更新时间:2023-12-05 07:07:39 26 4
gpt4 key购买 nike

我正在使用 Sprache 解析文件的一部分,如下所示:

OneThing=Foo
AnotherThing=Bar
YetAnotherThing=Baz

所有三行都是强制性的,但它们可以以任何顺序出现。我有针对各个行的解析器,看起来像这样:

public static readonly Parser<string> OneThing = (
from open in Parse.String("OneThing=")
from rest in Parse.AnyChar.Except(Parse.LineTerminator).Many().Text()
from newLine in Parse.LineEnd
select rest
);

然后我将它们组合起来解析整个部分,如下所示:

public static readonly Parser<MyClass> Section = (
from oneThing in SectionGrammar.OneThing
from anaotherThing in SectionGrammar.AnotherThing
from yetAnotherThing in SectionGrammar.YetAnotherThing
select new MyClass(oneThing, anotherThing, yetAnotherThing)
);

但这只有在行以 OneThing、AnotherThing、YetAnotherThing 的顺序出现时才有效。我怎样才能更改它以允许行以任何顺序出现,但仍然强制每行应该出现一次?

非常感谢任何帮助!谢谢

最佳答案

我对 Sprache 非常天真,但一种可能很冗长的方法是为每一行选择每个选项的元组,然后在最终选择中过滤元组数组。像这样的东西:

public static readonly Parser<MyClass> Section = (
select a from (from oneThing in SectionGrammar.OneThing select Tuple.Create(oneThing, null, null))
.Or(from anotherThing in SectionGrammar.AnotherThing select Tuple.Create(null, anotherThing, null))
.Or(from yetAnotherThing in SectionGrammar.YetAnotherThing select Tuple.Create(null, null, yetAnotherThing))

select b from (from oneThing in SectionGrammar.OneThing select Tuple.Create(oneThing, null, null))
.Or(from anotherThing in SectionGrammar.AnotherThing select Tuple.Create(null, anotherThing, null))
.Or(from yetAnotherThing in SectionGrammar.YetAnotherThing select Tuple.Create(null, null, yetAnotherThing))

select c from (from oneThing in SectionGrammar.OneThing select Tuple.Create(oneThing, null, null))
.Or(from anotherThing in SectionGrammar.AnotherThing select Tuple.Create(null, anotherThing, null))
.Or(from yetAnotherThing in SectionGrammar.YetAnotherThing select Tuple.Create(null, null, yetAnotherThing))

select new MyClass(
new[] { a, b, c }.Where(i => i.Item1 != null).Select(i => i.Item1).First(),
new[] { a, b, c }.Where(i => i.Item2 != null).Select(i => i.Item2).First(),
new[] { a, b, c }.Where(i => i.Item3 != null).Select(i => i.Item3).First()
));

不过感觉应该有更好的办法。如果您对我说有 20 行具有独特的解析并且可能有不同的顺序,那么上面的代码也不是很可扩展。

关于c# - 如何使用 Sprache 解析可以以任何顺序出现的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62060732/

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