【问题标题】:CSV Parsing Options with .NET [closed].NET 的 CSV 解析选项 [关闭]
【发布时间】:2018-07-27 18:38:24
【问题描述】:

我正在查看基于 MS 堆栈的分隔文件(例如 CSV、制表符分隔等)解析选项,特别是 .net。我唯一排除的技术是 SSIS,因为我已经知道它不能满足我的需求。

所以我的选择似乎是:

  1. Regex.Split
  2. TextFieldParser
  3. OLEDB CSV Parser

我必须满足两个标准。首先,给定以下文件,其中包含两个逻辑数据行(总共五个物理行):

101, Bob, "Keeps his house ""clean"".
Needs to work on laundry."
102, Amy, "Brilliant.
Driven.
Diligent."

解析结果必须产生两个逻辑“行”,每行由三个字符串(或列)组成。第三行/列字符串必须保留换行符!换句话说,由于“未闭合”文本限定符,解析器必须识别行“继续”到下一个物理行的时间。

第二个标准是分隔符和文本限定符必须是可配置的,每个文件。这里有两个字符串,取自不同的文件,我必须能够解析:

var first = @"""This"",""Is,A,Record"",""That """"Cannot"""", they say,"","""",,""be"",rightly,""parsed"",at all";
var second = @"~This~|~Is|A|Record~|~ThatCannot~|~be~|~parsed~|at all";

字符串“first”的正确解析是:

  • 这个
  • 是,A,记录
  • 他们说“不能”,
  • _
  • _
  • 是
  • 正确
  • 已解析
  • 完全没有

“_”只是表示捕获了一个空白 - 我不希望出现文字下划线。

可以对要解析的平面文件做出一个重要假设:每个文件将有固定数量的列。

现在深入了解技术选项。

正则表达式

首先,许多响应者评论说正则表达式“不是实现目标的最佳方式”。但是,我确实找到了commenter who offered an excellent CSV regex:

var regex = @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))";
var Regex.Split(first, regex).Dump();

应用于字符串“first”的结果非常好:

  • “这个”
  • “是,A,记录”
  • “那个”“不能”,他们说,”
  • ""
  • _
  • “是”
  • 正确
  • “已解析”
  • 完全没有

如果引号被清理了会很好,但我可以轻松地将其作为后期处理步骤来处理。否则,此方法可用于解析示例字符串“first”和“second”,前提是相应地针对波浪号和管道符号修改正则表达式。太棒了!

但真正的问题与多行标准有关。在将正则表达式应用于字符串之前,我必须从文件中读取完整的逻辑“行”。不幸的是,我不知道要读取多少物理行来完成逻辑行,除非我有一个正则表达式/状态机。

所以这变成了一个“鸡和蛋”的问题。我最好的选择是将整个文件作为一个巨大的字符串读入内存,然后让正则表达式整理出多行(我没有检查上面的正则表达式是否可以处理)。如果我有一个 10 gig 的文件,这可能有点不稳定。

转到下一个选项。

TextFieldParser

三行代码将使这个选项的问题显而易见:

var reader = new Microsoft.VisualBasic.FileIO.TextFieldParser(stream);
reader.Delimiters = new string[] { @"|" };
reader.HasFieldsEnclosedInQuotes = true;

分隔符配置看起来不错。但是,“HasFieldsEnclosedInQuotes”是“游戏结束”。我很惊讶分隔符可以任意配置,但相比之下,除了引号之外,我没有其他限定符选项。请记住,我需要对文本限定符进行配置。再说一遍,除非有人知道 TextFieldParser 配置技巧,否则游戏就结束了。

OLEDB

一位同事告诉我,这个选项有两个主要缺点。首先,它对于大型(例如 10 gig)文件的性能很差。其次,有人告诉我,它会猜测输入数据的数据类型,而不是让您指定。不好。

帮助

所以我想知道我弄错的事实(如果有的话),以及我错过的其他选项。也许有人知道陪审团绑定 TextFieldParser 以使用任意分隔符的方法。也许 OLEDB 已经解决了上述问题(或者可能从未遇到过?)。

你说什么?

【问题讨论】:

标签: c# .net parsing


【解决方案1】:

您是否尝试搜索已经存在的 .NET CSV parser? This one 声称处理多行记录的速度明显快于 OLEDB。

【讨论】:

  • FastCSV 是一个相当受欢迎的库。
  • 是的,我环顾四周——这就是我提到三个选项的原因。问题是有更多的选择,但它们是否符合我的标准是一个非常缓慢的过程。我希望有人已经知道正确的选择。
  • 我使用nuget.org/packages/CsvHelper纯粹是根据nuget上的下载量(搜索链接nuget.org/packages?q=csv)
【解决方案2】:

我不久前将其作为一个轻量级的独立 CSV 解析器编写。我相信它可以满足您的所有要求。试一试,知道它可能不是防弹的。

如果它对您有用,请随意更改命名空间并不受限制地使用。

namespace NFC.Portability
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.IO;
    using System.Linq;
    using System.Text;

    /// <summary>
    /// Loads and reads a file with comma-separated values into a tabular format.
    /// </summary>
    /// <remarks>
    /// Parsing assumes that the first line will always contain headers and that values will be double-quoted to escape double quotes and commas.
    /// </remarks>
    public unsafe class CsvReader
    {
        private const char SEGMENT_DELIMITER = ',';
        private const char DOUBLE_QUOTE = '"';
        private const char CARRIAGE_RETURN = '\r';
        private const char NEW_LINE = '\n';

        private DataTable _table = new DataTable();

        /// <summary>
        /// Gets the data contained by the instance in a tabular format.
        /// </summary>
        public DataTable Table
        {
            get
            {
                // validation logic could be added here to ensure that the object isn't in an invalid state

                return _table;
            }
        }

        /// <summary>
        /// Creates a new instance of <c>CsvReader</c>.
        /// </summary>
        /// <param name="path">The fully-qualified path to the file from which the instance will be populated.</param>
        public CsvReader( string path )
        {
            if( path == null )
            {
                throw new ArgumentNullException( "path" );
            }

            FileStream fs = new FileStream( path, FileMode.Open );
            Read( fs );
        }

        /// <summary>
        /// Creates a new instance of <c>CsvReader</c>.
        /// </summary>
        /// <param name="stream">The stream from which the instance will be populated.</param>
        public CsvReader( Stream stream )
        {
            if( stream == null )
            {
                throw new ArgumentNullException( "stream" );
            }

            Read( stream );
        }

        /// <summary>
        /// Creates a new instance of <c>CsvReader</c>.
        /// </summary>
        /// <param name="bytes">The array of bytes from which the instance will be populated.</param>
        public CsvReader( byte[] bytes )
        {
            if( bytes == null )
            {
                throw new ArgumentNullException( "bytes" );
            }

            MemoryStream ms = new MemoryStream();
            ms.Write( bytes, 0, bytes.Length );
            ms.Position = 0;

            Read( ms );
        }

        private void Read( Stream s )
        {
            string lines;

            using( StreamReader sr = new StreamReader( s ) )
            {
                lines = sr.ReadToEnd();
            }

            if( string.IsNullOrWhiteSpace( lines ) )
            {
                throw new InvalidOperationException( "Data source cannot be empty." );
            }

            bool inQuotes = false;
            int lineNumber = 0;
            StringBuilder buffer = new StringBuilder( 128 );
            List<string> values = new List<string>();

            Action endSegment = () =>
            {
                values.Add( buffer.ToString() );
                buffer.Clear();
            };

            Action endLine = () =>
            {
                if( lineNumber == 0 )
                {
                    CreateColumns( values );
                    values.Clear();
                }
                else
                {
                    CreateRow( values );
                    values.Clear();
                }

                values.Clear();
                lineNumber++;
            };

            fixed( char* pStart = lines )
            {
                char* pChar = pStart;
                char* pEnd = pStart + lines.Length;

                while( pChar < pEnd ) // leave null terminator out
                {
                    if( *pChar == DOUBLE_QUOTE )
                    {
                        if( inQuotes )
                        {
                            if( Peek( pChar, pEnd ) == SEGMENT_DELIMITER )
                            {
                                endSegment();
                                pChar++;
                            }
                            else if( !ApproachingNewLine( pChar, pEnd ) )
                            {
                                buffer.Append( DOUBLE_QUOTE );
                            }
                        }

                        inQuotes = !inQuotes;
                    }
                    else if( *pChar == SEGMENT_DELIMITER )
                    {
                        if( !inQuotes )
                        {
                            endSegment();
                        }
                        else
                        {
                            buffer.Append( SEGMENT_DELIMITER );
                        }
                    }
                    else if( AtNewLine( pChar, pEnd ) )
                    {
                        if( !inQuotes )
                        {
                            endSegment();
                            endLine();
                            //pChar++;
                        }
                        else
                        {
                            buffer.Append( *pChar );
                        }
                    }
                    else
                    {
                        buffer.Append( *pChar );
                    }

                    pChar++;
                }
            }

            // append trailing values at the end of the file
            if( values.Count > 0 )
            {
                endSegment();
                endLine();
            }
        }

        /// <summary>
        /// Returns the next character in the sequence but does not advance the pointer. Checks bounds.
        /// </summary>
        /// <param name="pChar">Pointer to current character.</param>
        /// <param name="pEnd">End of range to check.</param>
        /// <returns>
        /// Returns the next character in the sequence, or char.MinValue if range is exceeded.
        /// </returns>
        private char Peek( char* pChar, char* pEnd )
        {
            if( pChar < pEnd )
            {
                return *( pChar + 1 );
            }

            return char.MinValue;
        }

        /// <summary>
        /// Determines if the current character represents a newline. This includes lookahead for two character newline delimiters.
        /// </summary>
        /// <param name="pChar"></param>
        /// <param name="pEnd"></param>
        /// <returns></returns>
        private bool AtNewLine( char* pChar, char* pEnd )
        {
            if( *pChar == NEW_LINE )
            {
                return true;
            }

            if( *pChar == CARRIAGE_RETURN && Peek( pChar, pEnd ) == NEW_LINE )
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// Determines if the next character represents a newline, or the start of a newline.
        /// </summary>
        /// <param name="pChar"></param>
        /// <param name="pEnd"></param>
        /// <returns></returns>
        private bool ApproachingNewLine( char* pChar, char* pEnd )
        {
            if( Peek( pChar, pEnd ) == CARRIAGE_RETURN || Peek( pChar, pEnd ) == NEW_LINE )
            {
                // technically this cheats a little to avoid a two char peek by only checking for a carriage return or new line, not both in sequence
                return true;
            }

            return false;
        }

        private void CreateColumns( List<string> columns )
        {
            foreach( string column in columns )
            {
                DataColumn dc = new DataColumn( column );
                _table.Columns.Add( dc );
            }
        }

        private void CreateRow( List<string> values )
        {
            if( values.Where( (o) => !string.IsNullOrWhiteSpace( o ) ).Count() == 0 )
            {
                return; // ignore rows which have no content
            }

            DataRow dr = _table.NewRow();
            _table.Rows.Add( dr );

            for( int i = 0; i < values.Count; i++ )
            {
                dr[i] = values[i];
            }
        }
    }
}

【讨论】:

    【解决方案3】:

    看看我发布到这个问题的代码:

    https://stackoverflow.com/a/1544743/3043

    它涵盖了大部分您的要求,并且更新它以支持替代分隔符或文本限定符不会花费太多时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-13
      • 2011-08-18
      • 2010-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      相关资源
      最近更新 更多