2011-04-14 58 views
0

我的項目有問題,請讓我在這裏解釋一下,我需要一些專家指導,因爲我是編程新手。 我有這樣的記事本中的數據:C#逐行解析文本數據

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

這是26線的數據,但我只只顯示例如3行。這裏按照優先級排序:

- 我只想讀取文本文件,然後提取數字。例如:10192 20351等。

-I具有ListView控件的6列,我想顯示號碼的每一行,在它的列

第1欄|第2列|第3列|第4列|第5列|柱6

10192 | 20351 | 30473 | 40499 |50449 | 60234 

-off當然,如果可能的話,每次5位數字的第一個2位是一個獨特的碼,所有我想要的只是3最後一位數字。例如:192 351 473 499 234.因此,每個數字將會被修改10.000。

我想我是你們的困惑很多,對不起,這是我當前的代碼

私人委託無效UpdateUiTextDelegate(字符串文本); private void serial_DataRecieved(object sender,System.IO.Ports.SerialDataReceivedEventArgs e) { //收集接收到我們'緩衝區'(字符串)的字符。 string received_data; received_data = 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> 

非常感謝,如果有人可以幫助我..

+3

你是什麼實際問題?我看到一份要求清單,但沒有解釋您遇到問題的位置。 – 2011-04-14 09:17:21

回答

0

編輯:添加的行變量通過灰分建議:

鑑於你沒有指定哪個對象你要寫入數據我asssume這是一個數據行命名的行:

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. 
} 
+0

除了[i]行以外的其他好處。我猜應該在for循環之外有另一個變量來增加行。否則,對於文件中的每一行,將創建6行。 – 2011-04-14 09:26:00

+0

對不起,它將成爲6列的列表框。我會試試看。 – Reza 2011-04-14 09:47:59

+0

listview不是列表框。抱歉讓人困惑。我正在使用C#Wpf。 – Reza 2011-04-14 09:56:38

2

我想你根本不需要正則表達式。您只需要按線路和空間分配string.Split

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

對於每一行,您可以通過按空格分隔行來獲取字段。

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

line.Split('');應該是lines.Split(''); – 2011-04-14 09:26:44

+0

@Ash Burlaczenko:不行,行是一行行數組。 – Homam 2011-04-14 09:30:46

1

像這樣的東西可能:

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

在那裏你將有各自具有的數據包含字符串屬性Columns項目的IEnumerable

非常未經檢驗的,雖然,但你的想法。

0
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(); 
    } 
} 
0

您不必爲此使用正則表達式。

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的換行符。它還會刪除可能導致其他答案失敗的其他空白。

+0

我可以使用這段代碼訪問每個已經分成幾組的數字嗎? – Reza 2011-04-18 15:27:39

+0

@Reza嗨,我不確定你的意思。但是你可以用'var asArray = result.ToArray();'將結果轉換爲數組,然後通過索引訪問各個行。 – 2011-04-18 20:51:39

0

好的,這可能是矯枉過正,但你提到你想把數據放入一個listview(也許是一個數據網格?),在這種情況下,你可能想要將數據轉換成某種對象形式。這一切取決於你一旦掌握了數據後你將如何處理這些數據。

假設一旦你獲得了數據,你就想要操縱它或者做更多的事情,就可以嘗試這樣的事情 - 你應該可以直接將它放入一個新的控制檯應用程序中,運行。

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; } 
    } 
} 
+0

謝謝..它不是一個小文件。 3行我把它只是一個樣本。我有這樣的26行號碼。但我試了一下。 – Reza 2011-04-14 09:41:15

+0

在事情的宏偉計劃26行是小:) – 2011-04-14 10:39:00