在导入到 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/