这样的事情应该会有所帮助:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
class Production
{
public string Name;
public string[] Components;
public static IEnumerable<Production> Parse(string contents)
{
var rdr = new System.IO.StringReader(contents);
string line;
var productions = new List<Production>();
while(null != (line = rdr.ReadLine()))
{
if(string.IsNullOrEmpty(line))
continue;
productions.Add(ParseOne(line));
}
return productions;
}
public static Production ParseOne(string line)
{
var parts = line.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
return new Production{Name = parts[0], Components = parts.Skip(2).ToArray()};
}
}
您可以像这样使用 Production.Parse 方法:
static void Main()
{
var productions = Production.Parse(@"S -> NP VP
S -> Aux NP VP
NP -> Proper-Noun
NP -> Nominal
Nominal -> Noun
Nominal -> Nominal Noun
Nominal -> Nominal PP
VP -> Verb NP
VP -> Verb NP PP
PP -> Preposition NP");
// Or from a file like this:
productions = Production.Parse(File.ReadAllText("myProductions.txt));
}
编辑:要加入制作,请考虑按名称分组。
productions.GroupBy(p => p.Name, p => new Production{Name=p.Key, Components=p.SelectMany(x => x)});