一、引言
受朋友之托,處理一份點雲數據,格式:“X[m] Y[m] Z[m] R[dB] G[dB] B[dB]”,總共63w個點,轉換成的格式是:“點名,,X[m], Y[m], Z[m]”。如果經常有坐標文件轉換就使用代碼方法,偶爾使用的話就使用Excel。用Excel的話,直接把后綴名改成.xlsx,接下來就是對整列進行插入、更改等事情了,最后另存為txt格式或者dat格式。
二、知識准備
1、文件讀寫
2、字符串處理
三、需要注意的地方
1、60幾萬個點,數據量還行,所以思路和數據結構要格外注意,能省則省。鄙人昨天走了彎路,拿19萬個點測試時候花了0.75秒有點沾沾自喜,今天重新到回去看,寫的什么玩意兒,把代碼重新修改了一下,測試顯示,19萬個點0.45秒左右,63萬個點1.15秒左右。
2、文件讀寫要注意文件流的打開與關閉。
四、代碼
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 點雲轉pt { class Program { static void Main(string[] args) { //測時 Stopwatch st = new Stopwatch(); st.Start(); string wjming = "坐標" + "(" + DateTime.Now.ToString("yyyyMMddhhmmss") + ")"; string path = @"E:\C#\點雲轉pt2\點雲轉pt2\bin\Debug"; File.WriteAllText(path + "\\" + wjming + ".txt", null); List<坐標> result = diaoqu(@"C:\Users\Ouy_\Desktop\all-Octree (0.1).txt"); using (StreamWriter sw = new StreamWriter(wjming + ".txt")) { foreach (var item1 in result) { sw.WriteLine(item1.Name + ",," + item1.X + "," + item1.Y + "," + item1.H); } } st.Stop(); Console.WriteLine("OK!Time: " + st.Elapsed); } static List<坐標> diaoqu(string a) { FileStream fs = new FileStream(a, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); StreamReader m_streamReader = new StreamReader(fs); m_streamReader.BaseStream.Seek(0, SeekOrigin.Begin); int index = 0; string strLine = m_streamReader.ReadLine(); List<坐標> result = new List<坐標>(); // 從數據流中讀取每一行,直到文件的最后一行 while (strLine != null) { string[] s = strLine.Split(' ');//txt文件格式分隔符 try { 坐標 pt = new 坐標((++index).ToString(), s[0], s[1], s[2]); result.Add(pt); strLine = m_streamReader.ReadLine(); } catch (Exception ex) { Console.Write(ex.ToString()); } } fs.Close(); m_streamReader.Close(); return result; } } struct 坐標 { public string Name { get; set; } public string X { get; set; } public string Y { get; set; } public string H { get; set; } public 坐標(string name, string x, string y, string h) { Name = name; X = x; Y = y; H = h; } } }