繁体   English   中英

C#检查txt是否包含字符串并在其下面输出行

[英]C# Check if txt contains string and output the line below it

我正在开发一种聊天机器人,并且有一个txt文件,其中包含以Q,A,Q,A,Q,A格式显示的问题和答案:

狗是猫吗?

不,他们不是

猫是狗?

不,他们不是

我需要检查文本文件是否包含输入,然后将输出值设置为答案,该答案位于问题下方。 这是我到目前为止所拥有的。

    static string path = Path.Combine(Directory.GetCurrentDirectory(), "memory.txt");

    static IEnumerable<string> lines = File.ReadLines(path);
    static string inputValue;
    static string outputValue = " ";

        while (!shutdown)
        {
            Console.Write("User: ");
            inputValue = Console.ReadLine();
            inputValue = inputValue.ToLower();
            inputValue = inputValue.Trim(new Char[] { ' ', '.', ',', ':', ';', '*' });
            StringComparison comp = StringComparison.OrdinalIgnoreCase;

            if (inputValue == "hi" || inputValue == "hello" || inputValue == "greetings")
            {
                outputValue = "Hi";
            }
            else if (inputValue.Contains("how are you"))
            {
                outputValue = "Good";
            }
            else
            {

                if (File.ReadAllLines(path).Contains(inputValue))
                {
                    outputValue = //This is what i have to figure out
                }
                else
                {

                }

            }

            Console.Write("Computer: ");
            Console.WriteLine(outputValue);
            outputValue = " ";
        }
    }

我建议使用LinqSkipWhile

outputValue = File
  .ReadLines(path)
  .SkipWhile(line => line != inputValue)
  .Skip(1)
  .FirstOrDefault();

if (outputValue != null) {
  //TODO: outputValue has been found, put relevant code here  
}
// load the file in the list
List<string> lines = File.ReadAllLines(path);

// get the position of the question
int question_position = lines.IndexOf(inputValue);

// check if the question was found AND if there is a line below it with the answer
if (question_position >= 0 && lines.Count() > question_position + 1)
{
    // assign the answer to the outputValue
    outputValue = lines[question_position + 1];
}

不要使用File.ReadAllLines因为那样会将整个文件读入内存。 逐行读取而不是读取整个文件。 问题可能在第一行,因此为什么将整个文件读入内存。

string outputValue = "";
var lines = System.IO.File.ReadLines( path );
foreach( var thisLine in  lines) 
{
   if( thisLine.Contains( inputValue ) ) 
   {
      // Get the answer from the next line
      var answer = lines.Take( 1 ).FirstOrDefault();
      if( !string.IsNullOrWhiteSpace( answer ) ) 
      {
         outputValue = answer;
      }
   }
}

您可以在此处阅读我的答案以了解有关ReadAllLinesReadLines之间的区别的更多详细信息。

暂无
暂无

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

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