1

在我的 C# 程序中(此时),我的表单中有两个字段。一种是使用列表框的单词列表;另一个是文本框。我已经能够成功地将一个大单词列表从文本文件加载到列表框中。我还可以通过这种方式将列表框中的选定项目显示到文本框中:

private void wordList_SelectedIndexChanged(object sender, EventArgs e)
     {
          string word = wordList.Text;
          concordanceDisplay.Text = word;
     }

我有另一个本地文件,我需要在文本框中显示它的一些内容。在这个文件中,每个词条(如字典中的)前面都有一个#。因此,我想使用变量“word”并在此本地文件中搜索以将条目放入文本框中,如下所示:

#headword1
    entry is here...
    ...
    ...
#headword2
    entry is here...
    ...
    ...
#headword3
    entry is here...
    ...
    ...

你得到文本文件的格式。我只需要在该词之前用# 搜索正确的词条,然后从那里复制所有信息,直到文件中的下一个哈希值,然后将其放在文本框中。

显然,我是新手,所以要温柔。非常感谢。

PS 我使用 StreamReader 获取单词列表并将其显示在列表框中,如下所示:

StreamReader sr = new StreamReader("C:\\...\\list-final.txt");
       string line;
       while ((line = sr.ReadLine()) != null)
       {
           MyList.Add(line);
       }
       wordList.DataSource = MyList;
4

2 回答 2

3
var sectionLines = File.ReadAllLines(fileName) // shortcut to read all lines from file
    .SkipWhile(l => l != "#headword2") // skip everything before the heading you want
    .Skip(1) // skip the heading itself
    .TakeWhile(l => !l.StartsWith("#")) // grab stuff until the next heading or the end
    .ToList(); // optional convert to list
于 2012-05-28T03:24:19.570 回答
2
string getSection(string sectionName)
{
    StreamReader sr = new StreamReader(@"C:\Path\To\file.txt");
    string line;
    var MyList = new List<string>();
    bool inCorrectSection = false;
    while ((line = sr.ReadLine()) != null)
    {
        if (line.StartsWith("#"))
        {
            if (inCorrectSection)
                break;
            else
                inCorrectSection = Regex.IsMatch(line, @"^#" + sectionName + @"($| -)");
        }
        else if (inCorrectSection)
            MyList.Add(line);
    }
    return string.Join(Environment.NewLine, MyList);
}

// in another method
textBox.Text = getSection("headword1");

以下是检查该部分是否匹配的几种替代方法,粗略的顺序是它们在检测正确的部分名称方面的准确程度:

// if the separator after the section name is always " -", this is the best way I've thought of, since it will work regardless of what's in the sectionName
inCorrectSection = Regex.IsMatch(line, @"^#" + sectionName + @"($| -)");
// as long as the section name can't contain # or spaces, this will work
inCorrectSection = line.Split('#', ' ')[1] == sectionName;
// as long as only alphanumeric characters can ever make up the section name, this is good
inCorrectSection = Regex.IsMatch(line, @"^#" + sectionName + @"\b");
// the problem with this is that if you are searching for "head", it will find "headOther" and think it's a match
inCorrectSection = line.StartsWith("#" + sectionName);
于 2012-05-28T03:14:43.403 回答