从txt文件中读取并获取特定文本

时间:2014-12-01 19:23:01

标签: c# asp.net

阅读* .txt文件并获取文本的特定区域的最佳做法是什么?

我的* .txt文件如下所示:

[Product code]
MYPRODUCT-CODE123

[List price]
28.10

[Price]
20.30

[Weight]
10

[Quantity]
1

[Min quantity]
1

[Shipping freight]
N

[Free shipping]
N

[Product name]
My product name

目前我正在读这样的txt文件:

        String[] allfiles = System.IO.Directory.GetFiles(_path, "*.txt", System.IO.SearchOption.AllDirectories);

        foreach (string filePath in allfiles) {


            using (StreamReader sr = File.OpenText(filePath))
            {
                string s = sr.ReadToEnd();

            }
        }

我如何获取[产品代码]附近的文字,以及来自我的txt文件的其他“关键术语”

4 个答案:

答案 0 :(得分:2)

我只是使用带捕获组的正则表达式来抓取对,然后将它们加载到词典中:

var dict = Regex
               .Matches(str, @"\[([^\]]+)\]([^\[]+)")
               .Cast<Match>()
               .ToDictionary(match => match.Groups[1].ToString(), 
                             match => match.Groups[2].ToString().Trim());

//dict = { [Product Code, MYPRODUCT-CODE123], [List Price, 28.10], [Price, 20.30] ...}

如果您将数据保存在文本文件中,我强烈建议您以XML格式存储数据。它以后会为你节省麻烦。

答案 1 :(得分:1)

所以你有你的字符串s。让我们从那里开始。

拆分新行,将对放入字典,获取项目:

var lines = s.Split(
                new[] { Environment.NewLine }, 
                StringSplitOptions.RemoveEmptyEntries)
             .ToArray();

// pairing thanks to http://stackoverflow.com/questions/1624341/
var dictionary = lines.Where((x, i) => i < lines.Length)
                      .Select((x, i) => 
                          new KeyValuePair<string, string>(
                              x.Trim('[', ']'), // get rid of brackets
                              lines[i + 1]))
                      .ToDictionary(x => x.Key, x => x.Value);

var productCode = dictionary["Product code"];

答案 2 :(得分:0)

System.IO.StreamReader file = 
   new System.IO.StreamReader("Your txt file");

Dictionary<string, string> values = new Dictionary<string, string>();
string keyContainer = "";

while((line = file.ReadLine()) != null)
{
   if(line.Trim() == "")
      continue;

   if(values.Keys.Contains(line.Trin())
      continue;   

   if(line.StartsWith('[') && line.EndsWith("]")
   {
       keyContainer = line.Trim();
       values.Add(line.Trim(), "");
   }
   else
   {
       values[keyContainer] = line.Trim();    
   }
}

使用此代码,您将在Dictionary中获得该文件的所有值。它们看起来像这样:

Key=[Quantity]; Value=1

如果需要,可以在将密钥保存到字典中时删除括号。

答案 3 :(得分:0)

另一种方法:

    string[] lines = input.Replace(Environment.NewLine, "\n").Replace('\r', '\n').Split('\n');
    for (int q = 0; q < lines.Length; q++)
    {
        string line = lines[q];
        if (string.IsNullOrWhiteSpace(line))
            continue;

        if (line.StartsWith("[") && line.EndsWith("]"))
        {
            string key="";
            string value="";

            for (int i=1; i<line.Length - 1; i++)
            {
                key=key + line[i];
            }           

            value = lines[q + 1];
            q++;

            dictionary.Add(key, value);
        }
    }

    foreach (string k in dictionary.Keys)
    {
        Console.WriteLine(k + " ==> " + dictionary[k]);
    }