gpt4 book ai didi

c# - 解析文本文件并删除双引号内的逗号

转载 作者:行者123 更新时间:2023-11-30 14:00:46 26 4
gpt4 key购买 nike

我有一个文本文件需要转换成 csv 文件。我的计划是:

  • 逐行解析文件
  • 搜索双引号内的逗号并将其替换为空格
  • 然后删除所有双引号
  • 将行附加到新的 csv 文件

问题:我需要一个函数来识别双引号内的逗号并替换它。

这是一个示例行:

"MRS Brown","4611 BEAUMONT ST","","WARRIOR RUN, PA"

最佳答案

您的文件似乎已经是 CSV 投诉格式。任何优秀的 CSV 阅读器都能够正确阅读它。

如果您的问题只是正确读取字段值,那么您需要以正确的方式读取它。

这是一种方法:

using Microsoft.VisualBasic.FileIO; 


private void button1_Click(object sender, EventArgs e)
{
TextFieldParser tfp = new TextFieldParser("C:\\Temp\\Test.csv");
tfp.Delimiters = new string[] { "," };
tfp.HasFieldsEnclosedInQuotes = true;
while (!tfp.EndOfData)
{
string[] fields = tfp.ReadFields();

// do whatever you want to do with the fields now...
// e.g. remove the commas and double-quotes from the fields.
for (int i = 0; i < fields.Length;i++ )
{
fields[i] = fields[i].Replace(","," ").Replace("\"","");
}

// this is to show what we got as the output
textBox1.AppendText(String.Join("\t", fields) + "\n");
}
tfp.Close();
}

编辑:

我刚刚注意到问题已在 C#、VB.NET-2010 下提交。这是 VB.NET 版本,以防您使用 VB 进行编码。

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim tfp As New FileIO.TextFieldParser("C:\Temp\Test.csv")
tfp.Delimiters = New String() {","}
tfp.HasFieldsEnclosedInQuotes = True
While Not tfp.EndOfData
Dim fields() As String = tfp.ReadFields

'' do whatever you want to do with the fields now...
'' e.g. remove the commas and double-quotes from the fields.
For i As Integer = 0 To fields.Length - 1
fields(i) = fields(i).Replace(",", " ").Replace("""", "")
Next
'' this is to show what we got as the output
TextBox1.AppendText(Join(fields, vbTab) & vbCrLf)
End While
tfp.Close()
End Sub

关于c# - 解析文本文件并删除双引号内的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9889225/

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