[英]split strings and assign them to dictionary
I have a text file containing many lines which look like this: 我有一个包含许多行的文本文件,如下所示:
Flowers{Tulip|Sun Flower|Rose}
花{郁金香|太阳花|玫瑰}
Gender{Female|Male}
性别{女|男}
Pets{Cat|Dog|Rabbit}
宠物{猫|狗|兔子}
I know how to read lines from a file, but what's the best way to split and store the categories and their subitems in a dictionary afterwards? 我知道如何从文件中读取行,但是随后将类别及其子项目拆分和存储在字典中的最佳方法是什么? Let's say from a string array which contains all the above lines?
让我们说一个包含以上所有行的字符串数组?
The idea to use a regexp is right, but I prefer using named captures for readability 使用正则表达式的想法是正确的,但是我更喜欢使用命名捕获来提高可读性
var regexp = new Regex(@"(?<category>\w+?)\{(?<entities>.*?)\}");
var d = new Dictionary<string, List<string>>();
// you would replace this list with the lines read from the file
var list = new string[] {"Flowers{Tulip|Sun Flower|Rose}"
, " Gender{Female|Male}"
, "Pets{Cat|Dog|Rabbit}"};
foreach (var entry in list)
{
var mc = regexp.Matches(entry);
foreach (Match m in mc)
{
d.Add(m.Groups["category"].Value
, m.Groups["entities"].Value.Split('|').ToList());
}
}
You get a dictionary with the category as a key, and the values in a list of strings 您将获得一个以类别为键的字典,并且字符串列表中的值为
you can use the Key
and value
on this code 您可以在此代码上使用
Key
和value
string T = @"Flowers{Tulip|Sun Flower|Rose}
Gender{Female|Male}
Pets{Cat|Dog|Rabbit}";
foreach (var line in T.Split('\n'))//or while(!file.EndOfFile)
{
var S = line.Split(new char[] { '{', '|','}' }, StringSplitOptions.RemoveEmptyEntries);
string Key = S[0];
MessageBox.Show(Key);//sth like this
for (int i = 1 ; i < S.Length; i++)
{
string value = S[i];
MessageBox.Show(value);//sth like this
}
}
you can use this: 您可以使用此:
string line = reader.ReadLine();
Regex r = new Regex(@"(\w+){(\w+)}");
now loop the results of this regex: 现在循环此正则表达式的结果:
foreach(Match m in r.Matches(line)) {
yourDict.Add(m.Groups[1], m.Groups[2].Split(' '));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.