gpt4 book ai didi

c# - 如何使用 C# 将文件中的多个选项卡替换为单个逗号

转载 作者:行者123 更新时间:2023-11-30 23:01:04 26 4
gpt4 key购买 nike

我正在尝试从 .txt 文件创建 CSV。该文件包含制表符分隔的数据,但在某些情况下有多个制表符。我目前能够处理单个选项卡到逗号的转换,但是当我遇到多个选项卡时,我将其替换为多个逗号,这会弄乱电子表格。这是我当前的代码:

private void ConvertToCSV(ListBox listBox)
{
string txtpath = DIRPATH + listBoxFiles.SelectedItem + ".txt";
string csvpath = DIRPATH + listBoxFiles.SelectedItem + ".csv";

// Read through rows in the text file and replace tabs with
// commas

var lines = File.ReadAllLines(txtpath);
var csv = lines.Select(row => string.Join(",", row.Split('\t')));

// Replace the .txt extention with .csv

File.WriteAllLines(txtpath, csv);
System.IO.File.Move(txtpath, csvpath);

}

如有任何帮助,我们将不胜感激!

编辑:这是我在 txt 文件中的内容:TabsInTxtFile 运行上面的代码后,这是 Excel 中的结果:ExcelResult

最佳答案

首先,我使用 REGEX 将多标签替换为单个标签

例如,输入如下:

t       m   f           yf

正则表达式后的输出:

t   m   f   yf

代码正则表达式:

    public string Format(string s)
{
string strRegex = @"[\t]+";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strReplace = @"[\t]";
return myRegex.Replace(s, strReplace);
}

接下来,我和你一样,将制表符替换为 ,<​​/p>

private void ConvertToCSV(ListBox listBox)
{
string txtpath = DIRPATH + listBoxFiles.SelectedItem + ".txt";
string csvpath = DIRPATH + listBoxFiles.SelectedItem + ".csv";

// Read through rows in the text file and replace tabs with
// commas

var lines = File.ReadAllLines(txtpath);
var csv = lines.Select(row => string.Join(",", Format(row).Split('\t')));

// Replace the .txt extention with .csv

File.WriteAllLines(txtpath, csv);
System.IO.File.Move(txtpath, csvpath);

}

关于c# - 如何使用 C# 将文件中的多个选项卡替换为单个逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51265944/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com