【问题标题】:Parsing input string and adding to dictionary解析输入字符串并添加到字典
【发布时间】:2013-11-20 10:36:45
【问题描述】:

一些背景:

我目前正在学习 C# 并从事 ChatBot 项目。 Chatbot 将从用户输入中学习,通过解析每个用户输入的句子,并将每个单词放入字典中,句子中的每个单词作为键,后面的单词作为字典中的值。

我的第一个绊脚石是尝试循环遍历字符串以将单词放入字典中。

我的代码:

class Program
{
    static string userInput;
    static string val;
    static string key;

    static Dictionary<string, string> dict = new Dictionary<string, string>();



    static void Main(string[] args)
    {

        userInput = Console.ReadLine();

        string[] wordbits = userInput.Split(' ');



        for (int i = 0; i < wordbits.Length; i++)
        {
            key = wordbits[i];
            for (int j = 0; j < wordbits.Length; j++)
            {
                val = wordbits[(j + 1)];
            }

            dict.Add(key, val);
        }



    }
}

我遇到的错误是IndexOutOfRangeException,我认为这是因为循环正在句子中最后一个单词之后寻找一个单词,但该单词不存在。

关于如何解决此问题的任何建议?

【问题讨论】:

  • 尽量不要在你的 for 循环中包含最后一个单词,并在循环之后单独添加它
  • 整个过程非常简单,如下所示:wordbits.ToDictionary(x =&gt; x, x =&gt; wordbits[wordbits.Length - 1]),但我不确定你是否喜欢。或者只是wordbits.ToDictionary(x =&gt; x, x =&gt; wordbits.Last())

标签: c# parsing loops dictionary


【解决方案1】:
 for (int j = 0; j < wordbits.Length; j++)
 {
     val = wordbits[(j + 1)];
 }

这个不行,你可以改成:

 for (int j = 0; j < wordbits.Length-1; j++)
 {
     val = wordbits[(j + 1)];
 }

或者只是改变(但这会改变逻辑):

 val = wordbits[j];

因为您在最后一次迭代中访问 wordbits[wordbits.Length] 时遇到了异常,所以数组的索引从 0 到 length-1

编辑

好的,我明白了,您得到的值如下:key value key value key value,将您的逻辑更改为:

    for (int i = 0; i < wordbits.Length-1; i+=2)
    {
        key = wordbits[i];
        val = wordbits[(i + 1)];

        dict.Add(key, val);
    }

它将向您的字典添加键和值。在您的逻辑中,内部 for 再次循环遍历 wordbits 的所有值,因此它不起作用,那里不需要 for 循环。

【讨论】:

  • 谢谢!真的很有帮助! :)
【解决方案2】:

这里不需要这么多循环,传入key即可,如果存在则更新值,否则添加新条目:

userInput = Console.ReadLine();
var matches = Regex.Matches(userInput,@"\w+\s+\w+");
foreach(Match m in matches){
  if(m.Success){
    var w = m.Value.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    dict[w[0]] = w[1];
  }
}

请注意,代码不会检查用户的无效输入。所有的输入应该是这样的:

word1 value1 word2 value2 word3 value3 ...
//after collecting matches, we will the following matches:
word1 value1
word2 value2
word3 value3
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    相关资源
    最近更新 更多