【发布时间】:2017-07-05 21:17:08
【问题描述】:
我有一个包含点列表的文本文件:
要点: 类型 5, 对象 ID 2, 设备类型猫, 标签“地址-1”, 描述“小猫”, 单位“磅”,
要点: 类型 5, 对象 ID 2, 设备类型猫, 标记“地址-2”, 描述“橙色小猫”, 单位“磅”,
要点: 类型 2, 对象 ID 3, 设备型狗, 标记“地址 5”, 描述“棕色狗”, 单位“磅”,
据此,我想创建我的类“Cat”的实例(在本例中为 2),其中包含此文本文件中的标记和描述(然后将它们放入 Cats 列表中)。我只想从类型 5 的点(那些是猫)中获取描述和标签。
我不确定获得我想要的字符串的最佳方法是什么。我需要在整个文件中搜索类型 5 的所有点,然后对于每个点,获取描述和标签并将其添加到新 Cat。
public static void Main()
{
string line;
List<Cat> catList = new List<Cat>();
StreamReader file = new StreamReader(@"C:\Config\pets.txt");
while((line = file.ReadLine()) != null)
{
string[] words = line.Split(',');
catList.Add(new Cat cat1)
}}
我最终这样做了:
public static List<List<string>> Parse()
{
string filePath = @"C:\Config\pets.txt";
string readText = File.ReadAllText(filePath);
string[] stringSeparators = new string[] { "POINT:" }; //POINT is the keyword the text will be split on
string[] result;
result = readText.Split(stringSeparators, StringSplitOptions.None);
List<List<string>> catData = new List<List<string>>();
//split the text into an list of pieces
List<string> tags = new List<string>(); //tags go here
List<string> descriptions = new List<string>(); //descriptions go here
foreach (string s in result)
{
if (s.Contains("TYPE 5")) //TYPE 5 = CAT
{
string[] parts = s.Split(','); //split the cat by commas
string chop = "'"; //once tags and descriptions have been found, only want to keep what is inside single quotes ie 'orange kitty'
foreach (string part in parts)
{
if (part.Contains("TAG"))
{
int startIndex = part.IndexOf(chop);
int endIndex = part.LastIndexOf(chop);
int length = endIndex - startIndex + 1;
string path = part.Substring(startIndex, length);
tag = tag.Replace(chop, string.Empty);
tags.Add(tag);
//need to create instance of Cat with this tag
}
if (part.Contains("DESCRIPTION"))
{
int startIndex = part.IndexOf(chop);
int endIndex = part.LastIndexOf(chop);
int length = endIndex - startIndex + 1;
string description = part.Substring(startIndex, length);
description = description.Replace(chop, string.Empty);
descriptions.Add(description);
//need to add description to Cat instance that matches associated tag
}
}
}
}
catData.Add(tags);
catData.Add(descriptions);
return catData;
【问题讨论】:
-
逐行读取文件,解析行并创建类的实例,然后将其添加到列表中。开始工作,然后问你写的代码有没有问题
-
到目前为止你有什么?你有读取文件的代码吗?你有一个代表你想要填充的对象的类吗?给我们看相关代码!
-
对于字符串解析,您可以使用正则表达式。如果你不方便,它看起来很简单,只需手动解析,查找关键字和逗号。
-
添加了我最近的尝试。我想通过关键字'point'而不是字符来分割文件 - 问题是我没有看到任何可以分割的字符。有没有另一种方法可以将文件分成更小的块,然后我可以解析?
-
这是一个开始。现在查看单词中的第一个条目,如果它与搜索到的文本匹配,则取第四个和第五个条目,删除不需要的部分(标签/描述),其余部分设置 Cat 类的属性