使用 C# 解析文本文件

发布于 2024-09-13 13:23:28 字数 539 浏览 8 评论 0原文

寻找一种解析此文本文件的好方法,使用 C# 用黄色框突出显示值。每个部分都由一个我忘记突出显示的术语# 来描述。尝试过这个:

string fileName = "ATMTerminalTotals.txt";
StreamReader sr = new StreamReader(fileName);
string[] delimiter = new string[] { " " };
while (!sr.EndOfStream)
{
     string[] lines = sr.ReadLine().Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
     foreach (string line in lines)
     {
         Console.WriteLine(line);
     }
}
Console.ReadLine();

可以肯定地说我正在正确阅读行并删除“空格”。尽管作为编程的业余爱好者,不确定是否有有效的方法来准确地“知道”我正在从这份报告中获取我需要的值。有什么建议吗?

Looking for a good way to parse out of this text file, the values highlighted with the yellow boxes using C#. Each section is delineated by a TERM # which I forgot to highlight. Tried this:

string fileName = "ATMTerminalTotals.txt";
StreamReader sr = new StreamReader(fileName);
string[] delimiter = new string[] { " " };
while (!sr.EndOfStream)
{
     string[] lines = sr.ReadLine().Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
     foreach (string line in lines)
     {
         Console.WriteLine(line);
     }
}
Console.ReadLine();

Safe to say I am reading lines correctly and removing "white spaces." Although, as an amateur to programming, not sure of a valid way to accurately "know" that I am getting the values from this report that I need. Any advice?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

流星番茄 2024-09-20 13:23:28

我已经用一个非常简单的程序来测试这个来解析给定的文件,
基本上我创建了两个基本类,一个页面类包含终端报告类的集合(tran 类型行)
这些行甚至可以表示为事务和计费类,

首先解析数据,设置所需的参数,最后只是访问属性,

只是让它尽可能简单,没有错误处理等...它只是为了给出你知道我是如何开始解决这类任务的,希望它能帮助

亚当

namespace TerminalTest
{
    class Program
    {
        public class TerminalReport
        {
            public string Word { get; set; }

            public int Denials { get; set; }

            public int Approvals { get; set; }

            public int Reversals { get; set; }

            public double Amount { get; set; }

            public int ON_US { get; set; }

            public int Alphalink { get; set; }

            public int Interchange { get; set; }

            public int Surcharged { get; set; }

            public static TerminalReport FromLine(string line)
            {
                TerminalReport report = new TerminalReport();
                report.Word = line.Substring(0, 11);
                line = line.Replace(report.Word, string.Empty).Trim();
                string[] split = line.Split(' ');
                int i = 0;
                // transaction summary
                report.Denials = int.Parse(split[i++]);
                report.Approvals = int.Parse(split[i++]);
                report.Reversals = int.Parse(split[i++]);
                report.Amount = double.Parse(split[i++]);
                // billing counts
                report.ON_US = int.Parse(split[i++]);
                report.Alphalink = int.Parse(split[i++]);
                report.Interchange = int.Parse(split[i++]);
                report.Surcharged = int.Parse(split[i++]);

                return report;
            }
        }

        public class TerminalPage
        {
            public int PageNumber { get; set; }

            public double TotalSurcharges { get; set; }

            public List<TerminalReport> Rows { get; set; }

            public TerminalPage(int num)
            {
                PageNumber = num;
                Rows = new List<TerminalReport>();
            }

            public int TotalDenials
            {
                get
                {
                    return rows.Sum(r => r.Denials);
                }
            }

            public int TotalApprovals
            {
                get
                {
                    return Rows.Sum(r => r.Approvals;
                }
            }

            public int TotalReversals
            {
                get
                {
                    return Rows.Sum(r => r.Reversals;
                }
            }

            public double TotalAmount
            {
                get
                {
                    return Rows.Sum(r => r.Amount);
                }
            }

            public int TotalON_US
            {
                get
                {
                    return Rows.Sum(r => r.ON_US);
                }
            }

            public int TotalAlphalink
            {
                get
                {
                     return Rows.Sum(r => r.Alphalink);
                }
            }

            public int TotalInterchange
            {
                get
                {
                     return Rows.Sum(r => r.Interchange);
                }
            }

            public int TotalSurcharged
            {
                get
                {
                     return Rows.Sum(r => r.Surcharged);
                }
            }
        }

        private static string CleanString(string text)
        {
            return Regex.Replace(text, @"\s+", " ").Replace(",", string.Empty).Trim();
        }

        private static List<TerminalPage> ParseData(string filename)
        {
            using (StreamReader sr = new StreamReader(File.OpenRead(filename)))
            {
                List<TerminalPage> pages = new List<TerminalPage>();

                int pageNumber = 1;
                TerminalPage page = null;
                bool parse = false;
                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();
                    line = CleanString(line);
                    if (line.StartsWith("TRAN TYPE"))
                    {
                        // get rid of the ----- line
                        sr.ReadLine();

                        parse = true;
                        if (page != null)
                        {
                            pages.Add(page);
                        }
                        page = new TerminalPage(pageNumber++);
                    }
                    else if (line.StartsWith("="))
                    {
                        parse = false;
                    }
                    else if (line.StartsWith("TOTAL SURCHARGES:"))
                    {
                        line = line.Replace("TOTAL SURCHARGES:", string.Empty).Trim();
                        page.TotalSurcharges = double.Parse(line);
                    }
                    else if (parse)
                    {
                        TerminalReport r = TerminalReport.FromLine(line);
                        page.Rows.Add(r);
                    }
                }
                if (page != null)
                {
                    pages.Add(page);
                }

                return pages;
            }
        }

        static void Main(string[] args)
        {
            string filename = @"C:\bftransactionsp.txt";
            List<TerminalPage> pages = ParseData(filename);

            foreach (TerminalPage page in pages)
            {
                Console.WriteLine("TotalSurcharges: {0}", page.TotalSurcharges);
                foreach (TerminalReport r in page.Rows)
                        Console.WriteLine(r.Approvals);

            }
        }
    }
}

i've tested this with a very simple program to parse the given file,
basically i've created two basic classes, a page class holding a collection of terminal report class (the tran type rows)
these rows maybe even can be represented as transaction and a billing class too

first parsed the data, setting the parameters needed and lastly just accessing the properties

just rushed it to be as simple as possible, no error handling etc... its just to give you a sense of how id start solving these kind of tasks, hope it helps

Adam

namespace TerminalTest
{
    class Program
    {
        public class TerminalReport
        {
            public string Word { get; set; }

            public int Denials { get; set; }

            public int Approvals { get; set; }

            public int Reversals { get; set; }

            public double Amount { get; set; }

            public int ON_US { get; set; }

            public int Alphalink { get; set; }

            public int Interchange { get; set; }

            public int Surcharged { get; set; }

            public static TerminalReport FromLine(string line)
            {
                TerminalReport report = new TerminalReport();
                report.Word = line.Substring(0, 11);
                line = line.Replace(report.Word, string.Empty).Trim();
                string[] split = line.Split(' ');
                int i = 0;
                // transaction summary
                report.Denials = int.Parse(split[i++]);
                report.Approvals = int.Parse(split[i++]);
                report.Reversals = int.Parse(split[i++]);
                report.Amount = double.Parse(split[i++]);
                // billing counts
                report.ON_US = int.Parse(split[i++]);
                report.Alphalink = int.Parse(split[i++]);
                report.Interchange = int.Parse(split[i++]);
                report.Surcharged = int.Parse(split[i++]);

                return report;
            }
        }

        public class TerminalPage
        {
            public int PageNumber { get; set; }

            public double TotalSurcharges { get; set; }

            public List<TerminalReport> Rows { get; set; }

            public TerminalPage(int num)
            {
                PageNumber = num;
                Rows = new List<TerminalReport>();
            }

            public int TotalDenials
            {
                get
                {
                    return rows.Sum(r => r.Denials);
                }
            }

            public int TotalApprovals
            {
                get
                {
                    return Rows.Sum(r => r.Approvals;
                }
            }

            public int TotalReversals
            {
                get
                {
                    return Rows.Sum(r => r.Reversals;
                }
            }

            public double TotalAmount
            {
                get
                {
                    return Rows.Sum(r => r.Amount);
                }
            }

            public int TotalON_US
            {
                get
                {
                    return Rows.Sum(r => r.ON_US);
                }
            }

            public int TotalAlphalink
            {
                get
                {
                     return Rows.Sum(r => r.Alphalink);
                }
            }

            public int TotalInterchange
            {
                get
                {
                     return Rows.Sum(r => r.Interchange);
                }
            }

            public int TotalSurcharged
            {
                get
                {
                     return Rows.Sum(r => r.Surcharged);
                }
            }
        }

        private static string CleanString(string text)
        {
            return Regex.Replace(text, @"\s+", " ").Replace(",", string.Empty).Trim();
        }

        private static List<TerminalPage> ParseData(string filename)
        {
            using (StreamReader sr = new StreamReader(File.OpenRead(filename)))
            {
                List<TerminalPage> pages = new List<TerminalPage>();

                int pageNumber = 1;
                TerminalPage page = null;
                bool parse = false;
                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();
                    line = CleanString(line);
                    if (line.StartsWith("TRAN TYPE"))
                    {
                        // get rid of the ----- line
                        sr.ReadLine();

                        parse = true;
                        if (page != null)
                        {
                            pages.Add(page);
                        }
                        page = new TerminalPage(pageNumber++);
                    }
                    else if (line.StartsWith("="))
                    {
                        parse = false;
                    }
                    else if (line.StartsWith("TOTAL SURCHARGES:"))
                    {
                        line = line.Replace("TOTAL SURCHARGES:", string.Empty).Trim();
                        page.TotalSurcharges = double.Parse(line);
                    }
                    else if (parse)
                    {
                        TerminalReport r = TerminalReport.FromLine(line);
                        page.Rows.Add(r);
                    }
                }
                if (page != null)
                {
                    pages.Add(page);
                }

                return pages;
            }
        }

        static void Main(string[] args)
        {
            string filename = @"C:\bftransactionsp.txt";
            List<TerminalPage> pages = ParseData(filename);

            foreach (TerminalPage page in pages)
            {
                Console.WriteLine("TotalSurcharges: {0}", page.TotalSurcharges);
                foreach (TerminalReport r in page.Rows)
                        Console.WriteLine(r.Approvals);

            }
        }
    }
}
榕城若虚 2024-09-20 13:23:28

我不确定我实际上会用空格将其分割。文本文件看起来像是分割成列。您可能想一次读取 10 个字符(或任何列的宽度)...我会将整个文件解析到字典中,这样您就可以获得像这样的条目

dict["WDL FRM CHK"]["# DENIALS"] = 236

,然后您可以轻松地从中检索您想要的值在那里,如果你将来需要更多的价值,你已经得到了它们。


或者,您可以使用正则表达式。您可以使用正则表达式获取第一个值,例如

^WDL FRM CHK\s+(?<denials>[0-9,]+)\s+(?<approvals>[0-9,]+)$

使用

m.Groups["approvals"]

I'm not sure I'd split it by spaces actually.. the textfile looks like its split into columns. You might want to read like 10 chars (or whatever the width of the column is) at a time... and I'd parse the whole file into a dictionary so you get entries like

dict["WDL FRM CHK"]["# DENIALS"] = 236

then you can easily retrieve the values you want from there, and if you ever need more values in the future, you've got them.


Alternatively, you can use regexs. You can grab the first value with a regex like

^WDL FRM CHK\s+(?<denials>[0-9,]+)\s+(?<approvals>[0-9,]+)$

using

m.Groups["approvals"]
美煞众生 2024-09-20 13:23:28

无论如何,我建议您使用 using 块包装您的 StreamReader

using (StreamReader sr = new StreamReader(fileName))
{
    // do stuff
}

阅读 MSDN

anyway I recommend you to wrap your StreamReader with using block:

using (StreamReader sr = new StreamReader(fileName))
{
    // do stuff
}

Read more on MSDN

难忘№最初的完美 2024-09-20 13:23:28

鉴于它似乎有一个标准的常规格式,我会使用正则表达式。您可以检查起始代码以找出您所在的行,然后解析数字并忽略空格的表达式很可能比手动处理更容易。

Given that it seems to have a standard, regular format, I would use regular expressions. You can check the starting code to figure out what row you're on, then an expression that will parse out the numbers and ignore whitespace will, very likely, be easier than handling it manually.

离笑几人歌 2024-09-20 13:23:28
using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication3
{
  class Program
  {
    static void Main(string[] args)
    {
      Regex exp = new Regex(@"WDL FRM CHK(\s)+[1-9,]+(\s)+(?<approvals>[1-9,]+)(\s)+");
      string str = "WDL FRM CHK   236   1,854   45,465  123     3";
      Match match = exp.Match(str);

      if (match.Success)
      {
        Console.WriteLine("Approvals: " + match.Groups["approvals"].Value);
      }

      Console.ReadLine();
    }
  }
}

改编自以下文章以解析您的一个号码:

using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication3
{
  class Program
  {
    static void Main(string[] args)
    {
      Regex exp = new Regex(@"WDL FRM CHK(\s)+[1-9,]+(\s)+(?<approvals>[1-9,]+)(\s)+");
      string str = "WDL FRM CHK   236   1,854   45,465  123     3";
      Match match = exp.Match(str);

      if (match.Success)
      {
        Console.WriteLine("Approvals: " + match.Groups["approvals"].Value);
      }

      Console.ReadLine();
    }
  }
}

Apdated from the following article to parse one of your numbers:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文