【问题标题】:C# parsing text data line by lineC#逐行解析文本数据
【发布时间】:2011-04-14 09:15:49
【问题描述】:

我的项目有问题,让我在这里解释一下,我需要一些专家指导,因为我是编程新手。 我在记事本中有这样的数据:

10192 20351 30473 40499 50449 60234    
10192 20207 30206 40203 50205 60226    
10192 20252 30312 40376 50334 60252

这是 26 行数据,但我仅显示 3 行数据。这是一些按优先级排序的规则:

-我只想读取文本文件然后提取数字。示例:10192 20351 等等。

-我有 6 列 ListView,我想在它的列中显示每一行数字

第 1 列 |第 2 栏 |第 3 栏 |第 4 栏 |第 5 栏 |第6栏

10192   | 20351   | 30473  | 40499  |50449  | 60234

-当然,如果可能的话,每 5 位数字的前 2 位是唯一的代码,我想要的只是最后 3 位。例如:192 351 473 499 234。所以每个数字都将取模 10.000。

我想我让你们很多人感到困惑,对不起,这是我当前的代码

私人委托 void UpdateUiTextDelegate(String Text); 私人无效serial_DataRecieved(对象发送者,System.IO.Ports.SerialDataReceivedEventArgs e) { // 将接收到的字符收集到我们的“缓冲区”(字符串)中。 字符串接收数据; 接收到的数据 = serial.ReadExisting(); Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(WriteData), received_data); }

    private void WriteData(String Text)
    {
        if (bufferData != "" || Text[0] == '1')
            bufferData += Text;
        if (bufferData.Length >= 35)
        {
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Rads\Desktop\Training06.txt", true))
            {
                file.WriteLine(bufferData);
            }
            listBox1.Items.Add(bufferData);
            bufferData = "";
        }
    }
    #endregion

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {

    }

    //Browse .txt file
    private void Browse_btn_Click(object sender, RoutedEventArgs e)
    {
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

        dlg.DefaultExt = ".txt";
        dlg.Filter = "Text document (.txt)|*.txt";

        Nullable<bool> result = dlg.ShowDialog();

        if (result == true)
        {
            string filename = dlg.FileName;
            textBox.Text = filename;
        }
    }

    private void Parsing_String(string filename)
    {
        List<Row> list = new List<Row>();

        foreach (String str in File.ReadLines(filename))
        {
            String[] strCols = str.Split(Convert.ToChar(" "));
            list.Add(new Row()
            {
                Column1 = strCols[0].Substring(2),
                Column2 = strCols[1].Substring(2),
                Column3 = strCols[2].Substring(2),
                Column4 = strCols[3].Substring(2),
                Column5 = strCols[4].Substring(2),
                Column6 = strCols[5].Substring(2),


            });
        }

        dg.ItemsSource = list;
    }

    public class Row
    {
        public string Column1 { get; set; }
        public string Column2 { get; set; }
        public string Column3 { get; set; }
        public string Column4 { get; set; }
        public string Column5 { get; set; }
        public string Column6 { get; set; }

    }

XAML 代码

<Window x:Class="SamplingData.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="368" Width="401" Loaded="Window_Loaded">

<TabControl Height="332" HorizontalAlignment="Left" Name="tabControl1" VerticalAlignment="Top" Width="380">
    <TabItem Header="Sampling" Name="Sampling">
        <Grid>
            <Label Content="DATA RECEIVED" Height="28" HorizontalAlignment="Left" Margin="6,6,0,0" Name="label1" VerticalAlignment="Top" />
            <Button Content="Connect" Height="23" HorizontalAlignment="Left" Margin="264,6,0,0" Name="ConnectButton" VerticalAlignment="Top" Width="75" Click="Connect_Comms" />
            <ListBox Height="222" HorizontalAlignment="Left" Margin="10,37,0,0" Name="listBox1" VerticalAlignment="Top" Width="329" />
        </Grid>
    </TabItem>
    <TabItem Header="Training" Name="tabItem1">
        <Grid>
            <Button Content="Training" Height="23" HorizontalAlignment="Left" Margin="243,28,0,0" Name="Train_Btn" VerticalAlignment="Top" Width="75" />
            <Button Content="Browse" Height="23" HorizontalAlignment="Left" Margin="243,6,0,0" Name="Browse_btn" VerticalAlignment="Top" Width="75" Click="Browse_btn_Click" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="6,7,0,0" Name="textBox" VerticalAlignment="Top" Width="231" Background="{x:Null}"></TextBox>
            <RadioButton Content="RadioButton" Height="16" HorizontalAlignment="Left" Margin="507,76,0,0" Name="radioButton1" VerticalAlignment="Top" />
            <DataGrid x:Name="dg" AutoGenerateColumns="False" Margin="0,57,0,0" DataContext="{Binding}">
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding Column1}" Header="Column 1"></DataGridTextColumn>
                    <DataGridTextColumn Binding="{Binding Column2}" Header="Column 2"></DataGridTextColumn>
                    <DataGridTextColumn Binding="{Binding Column3}" Header="Column 3"></DataGridTextColumn>
                    <DataGridTextColumn Binding="{Binding Column4}" Header="Column 4"></DataGridTextColumn>
                    <DataGridTextColumn Binding="{Binding Column5}" Header="Column 5"></DataGridTextColumn>
                    <DataGridTextColumn Binding="{Binding Column6}" Header="Column 6"></DataGridTextColumn>
                </DataGrid.Columns>
            </DataGrid>
        </Grid>
    </TabItem>
</TabControl>

如果有人可以帮助我,非常感谢..

【问题讨论】:

  • 您的实际问题是什么?我看到了一份要求列表,但没有说明您遇到问题的地方。

标签: c# regex parsing text


【解决方案1】:

我认为您根本不需要正则表达式。您只需要按行和按空格的string.Split

string[] lines = data.Split(Enviroment.NewLine);

对于每一行,你可以通过空格分割行来获取字段。

string[] fields = line.Split(' ');

【讨论】:

  • line.Split(' ');应该是lines.Split(' ');
  • @Ash Burlaczenko :不,行是行数组的一项。
【解决方案2】:

编辑:按照 Ash 的建议添加 Row 变量:

鉴于您没有指定要将数据写入哪个对象,我假设它是一个名为 Row 的数据行:

private void Parsing_String(string filename)    
{
    DataTable dt = CreateDataTable();
    foreach (String str in File.ReadLines(filename))
    {
      String[] strCols = str.Split(Convert.ToChar(" "));
      DataRow Row = dt.NewRow(); //Where dt is a DataTable
      for (int i =0; i < strCols.length; i++)
      {
           Row[i] = strCols[i].Substring(2); //This will start reading from the third character
      }
      dt.Rows.Add(Row);
     }
      listView1.ItemsSource = dt.Rows;
}

//**EDIT**: Just in case you don't have a datatable and you want to create a small one:

public DataTable CreateDataTable()
    {
        DataTable dt = new DataTable();

        new string[] { "Column 1", "Column 2", "Column 3", "Column 4", "Column 5", "Column 6" }
            .ToList()
            .ForEach(c => { dt.Columns.Add(new DataColumn(c)); });
        return dt;
    }

编辑:最后一次尝试(忽略上面的代码):

    private void Parsing_String(string filename)
    {
        List<Row> list = new List<Row>();

        foreach (String str in File.ReadLines(filename))
        {
            String[] strCols = str.Split(Convert.ToChar(" "));
            list.Add(new Row() 
            {
                Column1 = strCols[0].Substring(2),
                Column2 = strCols[1].Substring(2),
                Column3 = strCols[2].Substring(2),
                Column4 = strCols[3].Substring(2),
                Column5 = strCols[4].Substring(2),
                Column6 = strCols[5].Substring(2)
            });
        }

        dg.ItemsSource = list;
    }

    public class Row
    {
        public string Column1 { get; set; }
        public string Column2 { get; set; }
        public string Column3 { get; set; }
        public string Column4 { get; set; }
        public string Column5 { get; set; }
        public string Column6 { get; set; }
    }

然后在您的 xaml 中:

如果您想指定自定义标题,则必须对其进行更改,以便它不会自动生成列而是使用绑定,即:

   <DataGrid x:Name="dg" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Column1}" Header="Column 1"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Column2}" Header="Column 2"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Column3}" Header="Column 3"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Column4}" Header="Column 4"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Column5}" Header="Column 5"></DataGridTextColumn>
            <DataGridTextColumn Binding="{Binding Column6}" Header="Column 6"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>

编辑这将计算第一列的总数

protected int CalculateFirstColumnTotal(List<Row> list)
{
    int total = 0;
    foreach (Row row in list)
      total += int.Parse(row.Column1);
}

编辑

您实际上从未调用 Parsing_String 方法,请将以下行添加到浏览方法:

private void Browse_btn_Click(object sender, RoutedEventArgs e)    
{
    //Existing Code
    Parsing_String(textBox.Text);  //Add this line to the last line of the method.
}

【讨论】:

  • 除了 Row[i] 部分之外还不错。我猜应该在 for 循环之外还有另一个变量来增加行。否则将为文件中的每一行创建 6 行。
  • 对不起,这将是一个有 6 列的列表框。我试试看。
  • listview 不是列表框。很抱歉造成混淆。我正在使用 C# Wpf。
  • 在哪里可以找到数据表?因为我使用的是 c# 2010,但在我的工具箱中找不到任何数据表?
  • 在代码顶部添加 using 语句: using System.Data;我已经更改了代码,以便它将绑定到您的列表视图
【解决方案3】:

可能是这样的:

var result = from row in theFileAsString.Split('\n')
             select new {
                Columns = row.Split(' ').Select(s => s.Substring(2))
             }

您将有一个IEnumerable,其中每个项目都有一个属性Columns,其中包含带有数据的字符串。

虽然非常未经测试,但你明白了。

【讨论】:

    【解决方案4】:

    好的,这可能有点矫枉过正,但您提到您希望将数据放入列表视图(可能是数据网格?),在这种情况下,您可能希望将数据转换为某种对象形式。这实际上取决于您在获得数据后实际上将如何处理这些数据。

    假设一旦您获得了数据,您将想要对其进行操作或对其进行更多操作,请尝试类似这样的操作 - 您应该能够将其直接放入新的控制台应用程序并运行它。

    namespace ConsoleApplication6
    {
        using System;
        using System.Collections.Generic;
        using System.IO;
        using System.Text.RegularExpressions;
    
        class Program
        {
            static void Main(string[] args)
            {
                string filename = @"c:\test.txt";
    
                // Because you're working with a small file, we'll just read all the lines into memory
                List<LineData> processedLines = new List<LineData>();
                foreach (var line in File.ReadAllLines(filename))
                {
                    processedLines.Add(new LineData(line));
                }
    
                // Write out the line data to the console to prove that it has been read
                foreach (var processedLine in processedLines)
                {
                    Console.WriteLine(
                        "{0},{1},{2},{3},{4},{5}", 
                        processedLine.Column1, 
                        processedLine.Column2,
                        processedLine.Column3,
                        processedLine.Column4,
                        processedLine.Column5,
                        processedLine.Column6);
                }
            }
        }
    
        public class LineData
        {
            public LineData(string line)
            {
                // Regex basically means find two digits ("Prefix") followed by 3 digits ("Value")
                Regex regex = new Regex(@"(?<Prefix>\d{2})(?<Value>\d{3})");
                var lineMatches = regex.Matches(line);
                if (lineMatches.Count != 6)
                {
                    // You should really be throwing your own exception type...
                    throw new Exception("Expected 6 columns!");
                }
    
                this.Column1 = this.ExtractMatchData(lineMatches[0]);
                this.Column2 = this.ExtractMatchData(lineMatches[1]);
                this.Column3 = this.ExtractMatchData(lineMatches[2]);
                this.Column4 = this.ExtractMatchData(lineMatches[3]);
                this.Column5 = this.ExtractMatchData(lineMatches[4]);
                this.Column6 = this.ExtractMatchData(lineMatches[5]);
            }
    
            private string ExtractMatchData(Match match)
            {
                return match.Groups["Value"].Value;
            }
    
            public string Column1 { get; set; }
            public string Column2 { get; set; }
            public string Column3 { get; set; }
            public string Column4 { get; set; }
            public string Column5 { get; set; }
            public string Column6 { get; set; }
        }
    }
    

    【讨论】:

    • 谢谢..这毕竟不是一个小文件。 3行我把它只是一个样本。我有 26 个这样的行号。但我试一试。
    • 在事物的宏伟计划中,26 行很小:)
    【解决方案5】:
    using (var stream = File.Open(this.filename, FileMode.Open, FileAccess.Read)
    {
        var reader = new StreamReader(stream);
        var data = reader.ReadLine();
        while (!String.IsNullOrWhitespace(data))
        {
            string[] columns = data.Split(' ');
            Console.WriteLine(string.Format("{0} {1} {2} {3} {4} {5}", columns[0], columns[1],));
            data = reader.ReadLine();
        }
    }
    

    【讨论】:

      【解决方案6】:

      您不必为此使用正则表达式。

      var data = @"10192 20351 30473 40499 50449 60234
      10192 20207 30206 40203 50205 60226
      10192 20252 30312 40376 50334 60252";
      
      var result = from line in data.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries)
                   let splitted = line.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries)
                   select splitted.Select(s => s.Substring(2));
      

      或用于文件

      using System.IO; // In the top
      
      var result = from line in File.ReadLines("path")
                   let splitted = line.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries)
                   select splitted.Select(s => s.Substring(2));
      

      result 现在将包含一系列字符串(其中前两个字符被删除)。此版本适用于 Unix 和 Windows 换行符。它还删除了可能导致其他答案失败的额外空格。

      【讨论】:

      • 我可以用这段代码访问已经在数组中分割的每个数字吗?
      • @Reza 嗨,我不确定你的意思。但是您可以使用var asArray = result.ToArray(); 将结果转换为数组,然后按索引访问各个行。
      猜你喜欢
      • 2014-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-05
      • 1970-01-01
      • 2012-07-16
      相关资源
      最近更新 更多