有关如何实现从文本文件读取定值的示例代码 [英] Sample code on how to implement definite value reading from text files

查看:35
本文介绍了有关如何实现从文本文件读取定值的示例代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,先生,

美好的一天!

我想在C#控制台应用程序中索取示例代码,以了解如何实现以下方案.

示例场景:
(输入来自文本文件)(也在文本文件中输出)
我有三种动物(CAT,DOG,MOUSE),用户需要在猫,狗和鼠标上用几个数字(未知数字)命名,并且它们在特定的颜色(例如黑色,白色,棕色)之间也有所区别.并根据它们的名称和颜色计算特定动物的数量. (例如,狗类,名称:LASSIE,颜色:BLACK,WHITE和BROWN,获取计数:找到5个名称为LASSIE的黑狗,发现3个名称为LASSIE的白狗,发现2个名称为LASSIE的棕狗)

表格示例:
-----------------------------------------
动物名称为黑白色棕
-----------------------------------------
猫加菲猫2 1 5
CAT BELLA 1 4 3
CAT KITTA 7 9 6

狗拉西5 3 2
狗滑雪者2 1 4

MOUSE MOUSSY 1 3 5
鼠鼠3 6 9
鼠标力量6 2 2
MOUSE JIMM 1 0 1
-----------------------------------------
总计:28 26 37

唯一的固定变量是猫狗和老鼠,颜色为黑白色棕色,
确定值的未知数中有名称,用户可以指定不同的名称和数字.

先生,请在这方面需要您的帮助.

提前谢谢!

这是我的示例代码

Hi Sir,

Good day!

I wanted to ask for a sample code in C# console application, on how could I implement the following scenario.

Sample Scene:
(input came from a text file) (output in a text file also)
I have three animals (CAT, DOG, MOUSE), the user needs to give a name on cat, dog and mouse in a several numbers (unknown numbers), plus they are differentiated on particular colors like BLACK, WHITE, BROWN. And count the number of particular animals based on their names and colors. (eg. class DOG, name: LASSIE, color: BLACK, WHITE and BROWN, Get Count: 5 Black Dogs found with a name of LASSIE, 3 White dogs found with a name of LASSIE, 2 Brown dogs found with a name of LASSIE)

Table example:
-----------------------------------------
ANIMALS NAMES BLACK WHITE BROWN
-----------------------------------------
CAT GARFIELD 2 1 5
CAT BELLA 1 4 3
CAT KITTA 7 9 6

DOG LASSIE 5 3 2
DOG SKITTER 2 1 4

MOUSE MOUSSY 1 3 5
MOUSE RATTY 3 6 9
MOUSE MIGHTY 6 2 2
MOUSE JIMM 1 0 1
-----------------------------------------
TOTAL: 28 26 37

The only fix variables are cat dog and mouse, and the color black white brown,
the unknown of definite value there are the names, the user can give different names and numbers.

Please Sir, I need your help on this.

Thanks in advance!

here''s my sample code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.IO;
namespace Clustering_Test
{
    class Program
    {
        static void Main(string[] args)
        {
            // Variable declaration (animal names)
            string strAnimal = String.Empty;
            string catName;
            int garfieldBlackCtr = 0, garfieldWhiteCtr = 0, garfieldBrownCtr = 0;
            int BellaBlackCtr = 0, BellaWhiteCtr = 0, BellaBrownCtr = 0;
            int KittaBlackCtr = 0, KittaWhiteCtr = 0, KittaBrownCtr = 0;
            int LassieBlackCtr = 0, LassieWhiteCtr = 0, LassieBrownCtr = 0;
            int SkitterBlackCtr = 0, SkitterWhiteCtr = 0, SkitterBrownCtr = 0;
            int MoussyBlackCtr = 0, MoussyWhiteCtr = 0, MoussyBrownCtr = 0;
            int RattyBlackCtr = 0, RattyWhiteCtr = 0, RattyBrownCtr = 0;
            string dogName, dogColorCtr;
            string mouseName, mouseColorCtr;
            string strGarfield, strBella, strKitta;
            string strLassie, strSkitter;
            string strMoussy, strRatty;
            // Reading input text file
            string dirFile = @"C:\FileDir\Sample_Text.txt";
            string recLine;
            int recCounter = 0;
            StreamReader srTable = new StreamReader(dirFile);
            while ((recLine = srTable.ReadLine()) != null)
            {
                recCounter++;
                strAnimal = recLine.Substring(0, 5);
                if (strAnimal == "CAT")
                {
                    // Get the name of the cat
                    catName = recLine.Substring(12, 9);
                    if (catName.Trim() == Cat.GARFIELD)
                    {
                        // Get the color count
                        string valCatColor = recLine.Substring(23, 3);
                        garfieldBlackCtr = Convert.ToInt32(valCatColor.Trim());
                        Process.intGarfieldBlack += garfieldBlackCtr;
                        string valCatColor2 = recLine.Substring(35, 3);
                        garfieldWhiteCtr = Convert.ToInt32(valCatColor.Trim());
                        Process.intGarfieldWhite += garfieldWhiteCtr;
                        string valCatColor3 = recLine.Substring(47, 3);
                        garfieldBrownCtr = Convert.ToInt32(valCatColor.Trim());
                        Process.intGarfieldBrown += garfieldBrownCtr;
                        // and so on...with BELLA and KITTA
                        // but the risk on this code, if new cat name occurred,
                        // I don't know how to handle new names and what variable counters
                        // could handle them...  please help me on this sir. thanks

                    }
                }
                else if (strAnimal == "DOG")
                {
                    // Get the name of the dog
                    dogName = recLine.Substring(12, 9);
                    if (dogName.Trim() == Dog.LASSIE)
                    {
                        // Get the color count
                        string valDogColor = recLine.Substring(23, 3);
                        LassieBlackCtr = Convert.ToInt32(valDogColor.Trim());
                        Process.intLassieBlack += LassieBlackCtr;
                        string valDogColor2 = recLine.Substring(35, 3);
                        LassieWhiteCtr = Convert.ToInt32(valDogColor.Trim());
                        Process.intLassieWhite += LassieWhiteCtr;
                        string valDogColor3 = recLine.Substring(47, 3);
                        LassieBrownCtr = Convert.ToInt32(valDogColor.Trim());
                        Process.intLassieBrown += LassieBrownCtr;
                        // and so on... with SKITTER
                        // but the risk on this code, if new cat name occurred,
                        // I don't know how to handle new names and what variable counters
                        // could handle them...  please help me on this sir. thanks
                    }
                    else if (strAnimal == "MOUSE")
                    {
                        // Get the color count
                        string valMouseColor = recLine.Substring(23, 3);
                        MoussyBlackCtr = Convert.ToInt32(valMouseColor.Trim());
                        Process.intMoussyBlack += MoussyBlackCtr;
                        string valMouseColor2 = recLine.Substring(35, 3);
                        MoussyWhiteCtr = Convert.ToInt32(valMouseColor.Trim());
                        Process.intMoussyWhite += MoussyWhiteCtr;
                        string valMouseColor3 = recLine.Substring(47, 3);
                        MoussyBrownCtr = Convert.ToInt32(valMouseColor.Trim());
                        Process.intMoussyBrown += MoussyBrownCtr;
                        // and so on...with RATTY
                        // but the risk on this code, if new cat name occurred,
                        // I don't know how to handle new names and what variable counters
                        // could handle them...  please help me on this sir. thanks
                    }
                }
                // Computer total count
                Process.intTotalBlack = Process.intGarfieldBlack + Process.intBellaBlack + Process.intKittaBlack +
                                                Process.intLassieBlack + Process.intSkitterBlack +
                                                Process.intMoussyBlack + Process.intRattyBlack;
                Process.intTotalWhite = Process.intGarfieldWhite + Process.intBellaWhite + Process.intKittaWhite +
                                             Process.intLassieWhite + Process.intSkitterWhite +
                                             Process.intMoussyWhite + Process.intRattyWhite;
                Process.intTotalBrown = Process.intGarfieldBrown + Process.intBellaBrown + Process.intKittaBrown +
                                             Process.intLassieBrown + Process.intSkitterBrown +
                                             Process.intMoussyBrown + Process.intRattyBrown;
            }
        }
    }
    class Cat
    {
        // I make the name constant to parallel it to text file which is wrong
        // because another names of cat might appear on text file like SMITTEN, KIM, CATTY
        public const string GARFIELD = "Garfield";
        public const string BELLA = "Bella";
        public const string KITTA = "Kitta";
    }
    class Dog
    {
        // I make the name constant to parallel it to text file which is wrong
        // because another names of dog might appear
        public const string LASSIE = "Lassie";
        public const string SKITTER = "Skitter";
    }
    class Mouse
    {
        // I make the name constant to parallel it to text file which is wrong
        // because another names of mouse might appear
        public const string MOUSSY = "Moussy";
        public const string RATTY = "Ratty";
        public const string MIGHTY = "Mighty";
        public const string JIMM = "Jimm";
    }
    class COLOR
    {
        public string BLACK = "Black";
        public string WHITE = "White";
        public string BROWN = "Brown";
    }
    class Process
    {
        // this variable assignment is wrong because another name of animals might occur and
        // no variable counter assigned to them... I need help on this too
        // Cat Variable Counters
        public static int intGarfieldBlack = 0;
        public static int intGarfieldBrown = 0;
        public static int intGarfieldWhite = 0;
        public static int intBellaBlack = 0;
        public static int intBellaBrown = 0;
        public static int intBellaWhite = 0;
        public static int intKittaBlack = 0;
        public static int intKittaBrown = 0;
        public static int intKittaWhite = 0;
        // Dog Variable Counters
        public static int intLassieBlack = 0;
        public static int intLassieBrown = 0;
        public static int intLassieWhite = 0;
        public static int intSkitterBlack = 0;
        public static int intSkitterBrown = 0;
        public static int intSkitterWhite = 0;
        // Mouse Variable Counters
        public static int intMoussyBlack = 0;
        public static int intMoussyBrown = 0;
        public static int intMoussyWhite = 0;
        public static int intRattyBlack = 0;
        public static int intRattyBrown = 0;
        public static int intRattyWhite = 0;
        // Total Counters
        public static int intTotalBlack = 0;
        public static int intTotalBrown = 0;
        public static int intTotalWhite = 0;
    }
}

推荐答案

考虑使用字典存储从文件中解析出的数据,类似这样的方法可能会为您解决:

Consider using dictionaries to store the data parsed from the file, something like this might solve it for you:

using System;
using System.Collections.Generic;
using System.IO;

namespace SocketSample
{
    class Program
    {
        private static void ParseLine(string line, IDictionary<string, IDictionary<string, IDictionary<string, int>>> animals)
        {
            if (line.Trim() == String.Empty)
                return;

            try
            {
                string[] parts = line.Split(' ');
                string animal = parts[0];
                string name = parts[1];
                int blacks = Convert.ToInt32(parts[2]);
                int whites = Convert.ToInt32(parts[3]);
                int browns = Convert.ToInt32(parts[4]);

                if (!animals.ContainsKey(animal))
                    animals[animal] = new Dictionary<string, IDictionary<string, int>>();

                if (!animals[animal].ContainsKey(name))
                {
                    animals[animal][name] = new Dictionary<string, int>();
                    animals[animal][name]["Black"] = 0;
                    animals[animal][name]["White"] = 0;
                    animals[animal][name]["Brown"] = 0;
                }

                animals[animal][name]["Black"] += blacks;
                animals[animal][name]["White"] += whites;
                animals[animal][name]["Brown"] += browns;
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Failed to parse line \"{0}\", {1}", line, e.Message);
            }
        }

        private static void Dump(IDictionary<string, IDictionary<string, IDictionary<string, int>>> animals)
        {
            foreach(string animal in animals.Keys)
            {
                foreach(string name in animals[animal].Keys)
                {
                    foreach(string color in animals[animal][name].Keys)
                    {
                        Console.WriteLine("There are {0} {1} {2} named {3}", animals[animal][name][color], color, animal, name);
                    }
                }
            }
        }

        public static void Main(string[] args)
        {
            IDictionary<string, IDictionary<string, IDictionary<string, int>>> animals = new Dictionary<string, IDictionary<string, IDictionary<string, int>>>();
            foreach (string line in File.ReadAllLines(@"your_input_file_here.txt"))
            {
                ParseLine(line, animals);
            }
            Dump(animals);
        }
    }
}



请注意,这仅是示例,正确的解决方案将验证绑定的事物(例如动物类型).


希望这会有所帮助,
弗雷德里克(Fredrik)



Note that this is just an example and a proper solution would verify things that are bound (such as animal types).


Hope this helps,
Fredrik


这篇关于有关如何实现从文本文件读取定值的示例代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆