2014-12-01 85 views
0

读取* .txt文件并获取文本特定区域的最佳实践是什么?从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文件中的其他'关键条款'

回答

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格式的数据,如果你保持它的所有在文本文件中。它会在稍后为您节省这个麻烦。

+0

我不是试图存储的东西,我正在一个小应用程序,将创建一个基于文件夹结构* .csv文件。我明确同意你的意见。 – 2014-12-01 20:09:02

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"]; 
+1

附:目前没有在开发机器上,所以你可能需要调整编译 – 2014-12-01 19:34:25

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();  
    } 
} 

有了这个代码,你将不得不在字典文件的所有值。它们将如下所示:

Key=[Quantity]; Value=1 

如果您希望在字典中保存密钥时可以删除括号。

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]); 
    }