C# - 从 4 个文本文件生成随机字符串

C# - Generate Random String from 4 Textfiles

嘿,我想从 4 个不同的文本文件中生成随机文本。 第一个文件有 2 个文本行,第二个文件有 2 个文本行,第三个文件有 3 个文本行,第四个文件有 1 个文本行。 这样应该可以生成 2x2x3x1 不同的文本。

我不知道为什么,但程序总是生成 2 个不同的文本,然后无限循环运行。

知道我可以做些什么来避免这种情况吗? - 通常它应该以 4 个不同的文本结尾。

如果我只用 2 行添加到其他文本文件 1 行,这样所有文件都有 3 行,只有最后一个文本文件有 1 行它可以工作。

但通常它也应该适用于 2 行。

Lists count 2 Lines and randam should generate random number between 0 and 2 minus 1 so its alltimes random between 0 and 1 and should select 列表中的随机索引 0 或 1。但是有 2列表中的元素总是 select 相同的索引。

我使用以下代码:

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

namespace VKTextGenerator
{
    class Program
    {
        string sFullText = "";
        string sFirstTextPart = "";
        string sSecoundTextPart = "";
        string sThirdTextPart = "";
        string sLinkText = "";
        int iAnzahlTexte = 4;



        static void Main(string[] args)
        {
            Random rnd = new Random();
            Program self = new Program();

            List<string> allTexts = new List<string>();

            self.deleteFullTextFile();

            for (int i = 0; i < self.iAnzahlTexte; i++)
            {

                self.ReadFirstTextPart();
                Thread.Sleep(rnd.Next(10, 5000));
                self.ReadSecoundTextPart();
                Thread.Sleep(rnd.Next(10, 5000));
                self.ReadThirdTextPart();
                self.ReadLinkText();

                self.sFullText = self.sFirstTextPart + " " + self.sSecoundTextPart + " " + self.sThirdTextPart + " " + self.sLinkText;


                if (!allTexts.Contains(self.sFullText))
                {
                    allTexts.Add(self.sFullText);
                    self.AppendTextToFile();
                }
                else
                {
                    i--;
   
                }
            }
        }

        internal static string GetStringSha256Hash(string text)
        {
            if (String.IsNullOrEmpty(text))
                return String.Empty;

            using (var sha = new System.Security.Cryptography.SHA256Managed())
            {
                byte[] textData = System.Text.Encoding.UTF8.GetBytes(text);
                byte[] hash = sha.ComputeHash(textData);
                return BitConverter.ToString(hash).Replace("-", String.Empty);
            }
        }

        public void deleteFullTextFile()
        {
            string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            path = removeExeFromPathChar(path);
            path = path + @"\FinishedText\";
            VerifyDir(path);
            string fileName = "FullTexts.txt";

            if (File.Exists(path + fileName))
            {
                File.Delete(path + fileName);
            }
        }

        public void ReadFirstTextPart()
        {
            List<string> textList = new List<string>();
            Random rnd = new Random();

            string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            path = removeExeFromPathChar(path);
            path = path + @"\Config\";
            string fileName = "FirstTextPart.txt";

            textList = ReadTextFile(path + fileName);
            if (textList.Count > 0)
            {
                sFirstTextPart = textList[rnd.Next(0, textList.Count - 1)];
            }
        }

        public void ReadSecoundTextPart()
        {
            List<string> textList = new List<string>();
            Random rnd = new Random();

            string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            path = removeExeFromPathChar(path);
            path = path + @"\Config\";
            string fileName = "SecoundTextPart.txt";

            textList = ReadTextFile(path + fileName);
            if (textList.Count > 0)
            {
                sSecoundTextPart = textList[rnd.Next(0, textList.Count - 1)];
            }
        }

        public void ReadThirdTextPart()
        {
            List<string> textList = new List<string>();
            Random rnd = new Random();

            string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            path = removeExeFromPathChar(path);
            path = path + @"\Config\";
            string fileName = "ThirdTextPart.txt";

            textList = ReadTextFile(path + fileName);
            if (textList.Count > 0)
            {
                sThirdTextPart = textList[rnd.Next(0, textList.Count - 1)];
            }
        }

        public void ReadLinkText()
        {
            List<string> textList = new List<string>();
            Random rnd = new Random();

            string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            path = removeExeFromPathChar(path);
            path = path + @"\Config\";
            string fileName = "LinkText.txt";

            textList = ReadTextFile(path + fileName);
            if (textList.Count > 0)
            {
                sLinkText = textList[rnd.Next(0, textList.Count - 1)];
            }
        }

        private static List<String> ReadTextFile(string path)
        {
            List<String> lines = new List<String>();
            using (StreamReader sr = new StreamReader(path, Encoding.UTF8))
            {
                while (sr.Peek() != -1)
                    lines.Add(sr.ReadLine());
            }
            return lines;
        }

        public void AppendTextToFile()
        {
            string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            path = removeExeFromPathChar(path);
            path = path + @"\FinishedText\";
            VerifyDir(path);
            string fileName = "FullTexts.txt";

            try
            {
                System.IO.StreamWriter file = new System.IO.StreamWriter(path + fileName, true);
                file.WriteLine(sFullText);
                file.Close();
            }
            catch (Exception) { }
        }

        public static String removeExeFromPathChar(String s)
        {
            int exeLength = "VKTextGenerator.exe".Length;

            return (s == null || s.Length == 0)
              ? null
              : (s.Substring(0, s.Length - exeLength));
        }

        public void VerifyDir(string path)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(path);
                if (!dir.Exists)
                {
                    dir.Create();
                }
            }
            catch { }
        }
    }
}

这是问题的缩小版。我现在意识到,问题是,如果我的文本文件中只有 2 行文本,我想 select 随机索引在 0 和 1 之间。对于你行的随机索引,我总是得到相同的结果 rnd.Next(0, xxx.count -1) 如果 xxx.count 只是 2 如果它的 3 或 4 没问题但是 2 它有问题我不明白为什么。代码如下。

请帮忙

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

namespace VKTextGenerator
{
    class Program
    {

        string sFullText = "";
        string sFirstTextPart = "";
        int iAnzahlTexte = 200;

        Random rnd = new Random();

        static void Main(string[] args)
        {

            Program self = new Program();

            List<string> allTexts = new List<string>();

            self.deleteFullTextFile();

            for (int i = 0; i < self.iAnzahlTexte; i++)
            {

                self.ReadFirstTextPart();
                Thread.Sleep(self.rnd.Next(10, 200));

                self.sFullText = self.sFirstTextPart + " " + self.sSecoundTextPart + " " + self.sThirdTextPart + " " + self.sLinkText;

                allTexts.Add(self.sFullText);
                self.AppendTextToFile();

            }
        }

        public static String removeExeFromPathChar(String s)
        {
            int exeLength = "VKTextGenerator.exe".Length;

            return (s == null || s.Length == 0)
                ? null
                : (s.Substring(0, s.Length - exeLength));
        }
        
        public void deleteFullTextFile()
        {
            string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            path = removeExeFromPathChar(path);
            path = path + @"\FinishedText\";
            string fileName = "FullTexts.txt";

            if (File.Exists(path + fileName))
            {
                File.Delete(path + fileName);
            }
        }

        public void ReadFirstTextPart()
        {
            List<string> textList = new List<string>();

            string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            path = removeExeFromPathChar(path);
            path = path + @"\Config\";
            string fileName = "FirstTextPart.txt";

            textList = ReadTextFile(path + fileName);
            if (textList.Count > 0)
            {
                sFirstTextPart = textList[rnd.Next(0, textList.Count - 1)];
            }
        }

        private static List<String> ReadTextFile(string path)
        {
            List<String> lines = new List<String>();
            using (StreamReader sr = new StreamReader(path, Encoding.UTF8))
            {
                while (sr.Peek() != -1)
                    lines.Add(sr.ReadLine());
            }
            return lines;
        }

        public void AppendTextToFile()
        {
            string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            path = removeExeFromPathChar(path);
            path = path + @"\FinishedText\";
            string fileName = "FullTexts.txt";

            try
            {
                System.IO.StreamWriter file = new System.IO.StreamWriter(path + fileName, true);
                file.WriteLine(sFullText);
                file.Close();
            }
            catch (Exception) { }
        }

    }
}

这是一篇短小精悍的文章。我不会调试你的原版,你应该可以用调试器来调试

using System;
using System.Collections.Generic;
using System.Text;

class Program {

    public static void Main() {
        string[] files = new string[] { "one.txt" , "two.txt", "three.txt", "four.txt" };
        List<string[]> contents = new();
        foreach (string file in files) {
            var lines = File.ReadAllLines(file);
            contents.Add(lines);
        }
        var rand = new Random();
   
        for (int k = 0; k < 4; k++) {
            var final = new StringBuilder();
            for (int i = 0; i < files.Length; i++) {
                int lineNo = rand.Next(contents[i].Length - 1);
                final.AppendLine(contents[i][lineNo]);
            }
            Console.WriteLine(final.ToString());
        }

    }
}

答案在文档中 https://docs.microsoft.com/en-us/dotnet/api/system.random.next?view=net-6.0

32-bit signed integer that is greater than or equal to 0 and less than MaxValue.

rand.Next(0,1)总是会生成0。我的代码中有同样的错误。

int lineNo = rand.Next(contents[i].Length - 1);

应该是

 int lineNo = rand.Next(contents[i].Length);

顺便说一句,我写代码是为了证明你的代码太长了