簡體   English   中英

文本文件解析錯誤

[英]Text File Parsing Error

我有一個100MB以上的這種格式的文本文件。 這里有一個樣本小文件。

and -0.436527 -0.515304 -0.002056 -0.227969 0.177528 0.201756...
with 0.101336 0.493859 -0.081095 -0.391502 -0.111579 0.388659...
voice -0.168610 0.413912 0.423446 0.484159 -0.546614 0.558571...

尾隨數字可以是100多個數字,包括正數和負數。 我根據一段建議使用了這段代碼來進行解析(查找某個文本並求和該文本的所有尾隨數字)。

double[] vectorOne = File.ReadLines(filename)
                    .Where(line => line.Contains("drop"))
                    .SelectMany(line => line.Split())
                    .Where(str => str.All(c => Char.IsDigit(c) || c == '-' || c == '.'))
                    .Select(str => Double.Parse(str, CultureInfo.InvariantCulture))
                    .ToArray();

            MessageBox.Show( "", vectorOne.Sum().ToString());

但是我收到以下錯誤: Input string was not in a correct format. at Double.Parse(str, CultureInfo.InvariantCulture)). Input string was not in a correct format. at Double.Parse(str, CultureInfo.InvariantCulture)).

任何幫助深表感謝!

您的問題就在這里:

.SelectMany(line => line.Split())

由於每行的末尾都有一個空格,因此也會為每行提供一個空條目(默認情況下,分割不會刪除空條目)

為了避免這種情況,您可以這樣做:

.SelectMany(line => line.Split(new char[] { ' ' },StringSplitOptions.RemoveEmptyEntries))

我用您的output.bin文件嘗試過,這次工作正常。

編輯:

double[] vectorOne = File.ReadLines("myOutput.bin")
                    .Where(line => line.Contains("drop"))
                    .Select(x => x.Trim())
                    .SelectMany(line => line.Split())
                    .Where(str => str.All(c => Char.IsDigit(c) || c == '-' || c == '.'))
                    .Select(str => Double.Parse(str, CultureInfo.InvariantCulture))
                    .ToArray();

這也起作用,您基本上在分割線之前修剪了線,刪除了最后一個空字符

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM