使用 ANTLR4 解析并返回双精度列表 [英] Parse and return a list of doubles using ANTLR4
本文介绍了使用 ANTLR4 解析并返回双精度列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 ANTLR4 在 C# 中将包含十进制数字的文件解析为 List
?一个完整的、有效的示例将说明所有部分是如何组合在一起的.
How can I parse a file containing a decimal numbers into a List<double>
in C# using ANTLR4? A complete, working example would illustrate how all the pieces go together.
输入文件如下所示:
12.34
45.67
89.10
推荐答案
这是对不同问题的旧答案的更新版本,展示了使用 C# 和 ANTLR4 完成此任务的一种方法.
This is an updated version of an older answer to a different question, showing one way to do this task using C# and ANTLR4.
grammar Values;
parse : (number ( LINEBREAK | EOF ) )* ;
number : NUMBER ;
NUMBER : DIGIT '.' DIGIT ;
DIGIT : [0-9]+ ;
WS : [ \t] -> channel(HIDDEN) ;
LINEBREAK : '\r'? '\n' | '\r' ;
倾听者
现在是实现监听器模式的类,现在监听编号:
using System;
using System.Collections.Generic;
namespace ANTLR_File_To_Arrray
{
public class ValuesListener : ValuesBaseListener
{
public List<double> doubles = new List<double>();
public override void ExitNumber(ValuesParser.NumberContext context)
{
doubles.Add(Convert.ToDouble(context.GetChild(0).GetText()));
}
}
}
主程序
最后是读取输入文件,设置一切,遍历树,并显示从暴露的List
中累积的double
值的主程序听众:
Main Program
And finally the main program that reads the input file, sets up everything, walks the tree, and displays the accumulated double
values from the List<double>
exposed by the listener:
using System;
using System.IO;
using Antlr4.Runtime;
using Antlr4;
using Antlr4.Runtime.Tree;
namespace ANTLR_File_To_Arrray
{
class Program
{
static void Main(string[] args)
{
const string SOURCEFILE = @"D:\prj\ANTLR_File_To_Arrray\ANTLR_File_To_Arrray\source1.txt";
using (StreamReader fileStream = new StreamReader(SOURCEFILE))
{
AntlrInputStream inputStream = new AntlrInputStream(fileStream);
ValuesLexer lexer = new ValuesLexer(inputStream);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
ValuesParser parser = new ValuesParser(tokenStream);
ValuesParser.ParseContext context = parser.parse();
ValuesListener listener = new ValuesListener();
ParseTreeWalker walker = new ParseTreeWalker();
bool built = parser.BuildParseTree;
walker.Walk(listener, context);
foreach (double d in listener.doubles)
Console.WriteLine(d);
Console.ReadKey();
}
}
}
}
这篇关于使用 ANTLR4 解析并返回双精度列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文