繁体   English   中英

使用C#比较数字并从文本文件中删除数字

[英]Compare numbers and remove numbers from a text file using C#

我创建了一个文本文件,其中一些随机浮点数从743.6到1500.4不等。 我正在找出一种方法来读取文本文件(我已经做过)并包含一个数字范围:让我们说(743.6 <= x <= 800)并删除超出范围的数字并最终存储最终值一个文本文件。

我设法写了一些代码来读取文本文件,这样当我编译它时会显示文本文件中的数字。 现在我不知道如何进一步发展。 这是我的代码,它能够运行编译。 此代码现在可以读取文本文件。

743.6

742.8

744.7

743.2

1000

1768.6

1750

1767

1780

1500

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ReadTextFile
{
    class Program
    {
        static void Main(string[] args)
        {
           string filePath = "C:\\Users\\Student\\Desktop\\ConsoleApp1\\ConsoleApp1\\Data\\TextFile.txt"; // File Direcotry

             List<string> lines = File.ReadAllLines(filePath).ToList();

             foreach (string line in lines)
             {
                 Console.WriteLine(line);
             }
             Console.ReadLine();
        }
    }
}

您需要读取所有行并使用空字符串替换最小值和最大值之间的所有值:

float min = 800.5F, max = 850.5F;
float currentValue;

var lines = File.ReadAllLines(usersPath);
var separator = ';'; // Change this according to which separator you're using between your values (if any)

foreach (var line in lines)
{
    foreach (string word in line.Trim().Split(separator))
    {
        if (float.TryParse(word.Trim(), out currentValue))
        {
            if (currentValue < min || currentValue > max)
            {
                line.Replace(word, "");
            }
        }
    }
}
File.WriteAllLines(usersPath, lines);

这会将文件读入内存,解析,过滤,然后用新数据覆盖现有文件。

File.WriteAllLines(filePath,
    File.ReadAllLines(filePath)
      .Select(x => double.Parse(x))
      .Where(x => x >= 800.5 && x <= 850.5)
      .Select(x => x.ToString()));

这是我的解决方案w /基本错误检测和一些稳健性由于使用正则表达式。 作为前言:使用正则表达式可能非常昂贵,并且它们并不总是如此。

在这种情况下,我认为他们没问题,因为你正在处理用户生成的输入(可能)。 正则表达式可以通过预编译来优化!

/*
    using System;
    using System.IO;
    using System.Text.RegularExpressions;
*/


void ReadFile(string filePath) {
    var fileInfo = default(FileInfo);
    var separator = @"[;\s:,]"; // This is a simple RegEx, can be done otherwise. This allows for a little more robustness IMO

    // VERY rudimentary error detection
    if (string.IsNullOrEmpty(filePath))
        throw new ArgumentNullException(nameof(filePath), "The path to the file must not be null or empty!");

    try {
        fileInfo = new FileInfo(filePath);
    } catch {
        throw new ArgumentException(nameof(filePath), "A valid path must be given!");
    }

    if (!fileInfo.Exists) {
        throw new IOException(string.Format("The file {0} does not exist!", filePath));
    }
    // END VERY rudimentary error checking

    var numberStrings = Regex.Split(File.ReadAllText(fileInfo.FullName), separator);
    // numberStrings is now an array of strings

    foreach (var numString in numberStrings) {
        if (decimal.TryParse(numString, out var myDecimal)) {
            // Do something w/ number
        } else {
            Debug.WriteLine("{0} is NaN!", numString);
        }
    }

}

这是代码的作用(写在我的头顶,请不要只是C&P它。首先测试它):

起初我们正在定义正则表达式。 这匹配范围内的任何字符(括号之间)。

然后我们执行非常基本的错误检查:

  • 如果传递的参数为null或为空则抛出异常
  • 如果我们无法将参数解析为FileInfo对象,则该路径可能无效。 抛出一个例外。
  • 如果该文件不存在,则抛出异常。

接下来我们将整个文本文件读入内存(不是基于每行!)并使用我们定义的正则表达式将整个字符串拆分为字符串数组。

最后,我们循环遍历我们的字符串数组并将每个数字解析为float(这就是你想要的。我个人会使用doubledecimal来获得更高的精度。请参阅Tom Scott的视频 。)。

如果字符串不解析为float,则可以相应地处理错误。 否则,使用变量myFloat执行您需要的操作。


编辑:我以为我读过你想要使用花车。 我的错; 我将数据类型更改为十进制。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM