【问题标题】:Parse Text File Into Dictionary in c#在 C# 中将文本文件解析为字典
【发布时间】:2017-07-21 17:15:46
【问题描述】:

如何逐行读取文本文件并将 :sometext: 行分配给字典的键,并将 :somtext: 行旁边的行分配给字典的值?例如,我如何制作下面的新行分隔列表:

我的文本文件:

:II: Own BIC / TID
COBADEFFDOC BIC could not be resolved
:IO: Correspondents BIC / TID
abc BIC identified as:
xyz AG,THE,pqe BRANCH
zxc

输出:

dictionary key ->  :II:
dictionary value ->  Own BIC / TID COBADEFFDOC BIC could not be resolved


dictionary key ->  :IO:
dictionary value ->  Correspondents BIC / TID
                             abc BIC identified as:
                              xyz AG,THE,pqe BRANCH
                              zxc

提前致谢。

【问题讨论】:

  • 你确定这是 c# 吗?无论如何,如果你想在 c# 中读取文件的内容,你可以使用“Stream”。你可以在这里读到它。 stackoverflow.com/questions/1404303/c-sharp-using-streams
  • 是从文本文件中读取.. 使用 StreamReader
  • string[] Array = Regex.Split(TextContext, @":[a-zA-Z0-9]*[a-zA-Z0-9]:")
  • 如果您想使用正则表达式,请参阅ideone.com/KwBlBF,只需将整个文件读入内存即可。请注意,将这种方法用于任意长度的文件绝不是一个好主意,仅适用于较小的文本文件。

标签: c# regex


【解决方案1】:

我已经尝试过了,几乎可以正常工作......就像这样......

string[] allLines = File.ReadAllLines(@"E:\stackfiletext.txt");

Dictionary<string, string> dictionary = new Dictionary<string, string>();
int pFrom = 0;
int pTo = 0;
string result = "";
string keyValue = "";
bool firstIterataion = true;

for (int i = 0; i < allLines.Length; i++)
{
  if (allLines[i] != null)
  {
    string line = allLines[i];
    if (allLines[i].Contains(":") & allLines[i].Count(x => x == ':') > 1)
    {
       if (!firstIterataion)
       {
          dictionary.Add(":" + result + ":", keyValue);
          keyValue = string.Empty;
       }
       pFrom = allLines[i].IndexOf(":") + ":".Length;
       pTo = allLines[i].LastIndexOf(":");
       result = allLines[i].Substring(pFrom, pTo - pFrom);
    }
    else if (!(allLines[i].Contains(":") & allLines[i].Count(x => x == ':') > 1))
    {
       keyValue += line;
    }
    firstIterataion = false;
   }
 }
if (!firstIterataion)
{
   dictionary.Add(":" + result + ":", keyValue);
   keyValue = string.Empty;
}

【讨论】:

  • 它工作不正常。它仅存储一个字典键并将所有字符串保留为值....
  • 让我再检查一下修改
  • 因此您也可以将其标记为答案。如果是这样@Krejivikas
猜你喜欢
  • 2018-10-12
  • 2012-11-08
  • 1970-01-01
  • 2018-04-02
  • 1970-01-01
  • 2015-02-24
  • 2017-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多