简体   繁体   English

如何拆分文本文件并使用整数?

[英]How can I split a text File and use the Integers?

I have a text file that displays students names and their scores. 我有一个文本文件,显示学生的姓名和分数。 The format looks like this: 格式如下:

James Johnson, 85
Robert Jones, 90
Lindsey Parks, 98
etc.

I have 10 names and scores all in the above format. 我有10个名字和分数都采用上述格式。 My problem is how do I split the text file by the delimiter, and use the integers from the text file 我的问题是如何用定界符分割文本文件,并使用文本文件中的整数

Here is my code so far: 到目前为止,这是我的代码:

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.FileIO;
namespace TextFiles1
{
  class Program    
  {        
    static void Main(string[] args)        
    {
      StreamReader sr = new StreamReader(@"C:\Users\jonda\Desktop\StudentScores.txt.txt");            
      string data = sr.ReadLine();            
      while (data != null)            
      {                
        Console.WriteLine(data);                
        string[] names = data.Split(',');                
        data = sr.ReadLine();            
      }            
      int total = 0;            
      double average = 0;            
      for (int index = 0; index < data.Length; index++)  
      {   
        total = total + data[index];
      }            
      average = (double)total / data.Length;            
      Console.WriteLine("Average = " + average.ToString("N2"));            
      int high = data[0];            
      for (int index = 0; index < data.Length; index++)                
      {                     
        if (data[index] > high)                     
        {                         
          high = data[index];                     
        }
      }            

      Console.WriteLine("Highest Score =" + high);           
      sr.Close();
      Console.ReadLine();
    }
  }
}

First of all, it's a good idea to separate file operations and other operations. 首先,将文件操作和其他操作分开是个好主意。 File operations are slow and costly, and should be completed as soon as possible. 文件操作缓慢且成本高昂,应尽快完成。 I would use a separate method, read the lines into a List and close the file operation first. 我将使用一种单独的方法,将这些行读入一个列表,然后首先关闭文件操作。

    private static List<string> ReadFile(string path)
    {
        List<string> records = new List<string>();
        using (StreamReader sr = new StreamReader(path))
        {
            while (!sr.EndOfStream)
                records.Add(sr.ReadLine());
        }
        return records;
    }

Then I would pass that list to another function and calculate average, max etc. 然后,我将该列表传递给另一个函数并计算平均值,最大值等。

private static void CalculateAverage(List<string> lines)
{
    char[] seperator = new char[] { ',' };
    List<int> scores = new List<int>();
    if (lines != null && lines.Count > 0)
    {
        foreach (string line in lines)
        {
            Console.WriteLine(line);
            string[] parts = line.Split(seperator);
            int val;
            if (int.TryParse(parts[1], out val))
                scores.Add(val);
        }
    }
    Console.WriteLine("Average: {0}", scores.Average());
    Console.WriteLine("Highest Score: {0}", scores.Max());
}

Then in your main program call the methods like this: 然后在您的主程序中调用如下方法:

List<string> lines = ReadFile(path);
CalculateAverage(lines);

Use Regex to find each person info and then split each of them and extract Name and Score . 使用Regex查找每个人的信息,然后拆分每个人并提取NameScore

Try like this: 尝试这样:

        var inputStr = "James Johnson, 85 Robert Jones, 90 Lindsey Parks, 98";
        var regex = new Regex(@"[A-z]* [A-z]*, [0-9]*");
        return  regex.Matches(inputStr)
            .OfType<Match>()
           .Select(p => p.Value.Split(','))
           .Select(p => new { Name = p[0], Score = Convert.ToInt32(p[1].Trim()) });

Result : 结果: 结果

I hope to be helpful for you :) 希望对您有所帮助:)

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

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