c# - 计算每行文本文件的制表符数

标签 c# text-files csv

在导入到 SQL Server 之前,我试图验证大型文本文件(8,000,000 多行)中的制表符数量是否正确。

我想我需要做这样的事情:

int count = 0;
char tab = "\t";
foreach(char c in tab) 
{
    if(char.IsTab(c)) 
    {
        count++;
    }
}

然而,这是不正确的。我需要这样做来验证文件的格式是否正确。

最佳答案

使用 Linq,您可以像这样获取错误行:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        int expectedNumberOfTabs = 5;

        List<string> rows = new List<string>
        {
            "col1 \t col2 \t col3 \t col4 \t col5 \t col6",
            "col1 \t col2 \t col3 \t col4 \t col5 \t col6",
            "col1 \t col2 \t col3 \t col4",
            "col1 \t col2 \t col3 \t col4 \t col5 \t col6 \t col7",
            "col1 \t col2 \t col3 \t col4 \t col5 \t col6",
            "col1 \t col2 \t col3 \t col4 \t col5",
            "col1 \t col2 \t col3 \t col4 \t col5 \t col6",
        };

        var badRows = rows.Where(row => row.Count(c => c == '\t') != expectedNumberOfTabs);
        foreach (var badRow in badRows)
        {
            // Fix the bad rows
            Console.WriteLine(badRow);
        }
    }
}

结果:

col1      col2      col3      col4
col1      col2      col3      col4      col5      col6      col7
col1      col2      col3      col4      col5

现在我不希望您一次将所有 8,000,000 多行读入内存。我想你会一次一行地阅读它们,一次处理一个,所以你真正感兴趣的这段代码是:

row.Count(c => c == '\t') != expectedNumberOfTabs

这将识别一个“坏”行供您修复。

示例方法

因为您要处理大量数据,所以您可能想尝试将文件中的行复制到新文件中,并在遇到错误行时修复它们。获得新的“固定”文件后,删除原始文件,然后将“固定”文件重命名回原始文件并将其导入数据库。

using System.IO;
using System.Linq;

public class Program
{
    public static void Main()
    {
        int expectedNumberOfTabs = 5;
        string originalFile = "MyFile.txt";
        string originalFileFixed = "MyFileFixed.txt";

        using (StreamReader sr = new StreamReader(originalFile))
        using (StreamWriter sw = new StreamWriter(originalFileFixed))
        {
            string line = sr.ReadLine();
            if (line.Count(c => c == '\t') != expectedNumberOfTabs)
            {
                // line = ...Fix the line
            }

            sw.WriteLine(line);
        }

        // Delete original file
        File.Delete(originalFile);
        // Rename the fixed file back to the original file
        File.Move(originalFileFixed, originalFile);

        // Import the file
    }
}

关于c# - 计算每行文本文件的制表符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31620844/

相关文章:

c# - 构建一个汇编程序

C# - 将文本文件的字符放入二维数组

python - 最有效地删除制表符分隔的 txt 的第 n 行

c# - CSV 文件内容到二维数组

python - Hadoop Reducer 没有结合所有 map 作业

c# - 如何为我的 linq 查询创建自定义存储表达式

java - Android 中的 “Could not find a part of the path” 错误

c# - 如何在 C++ 运行时组件内的 Windows Phone 8.1 XAML 应用程序中使用 C++ dll

python - 如何在特定点拆分字符串?

Oracle 如何将查询导出到文本/csv 文件