首页 > 解决方案 > 从字典中选择文本 - 单个单词与短语 - 例如“大米”与“米酒”

问题描述

问题

我正在用 C# 编写一个食谱解析器。我在富文本框中选择文本,其中食谱成分与字典条目匹配。我不确定如何处理(或描述)单个单词在字典中的短语中匹配(并重复计算)的情况

例子

在我的字典中,我有“大米”和“米酒”的条目。我想确保“大米”与“米酒”等词典中已有的短语不匹配。即“米酒”的“米”部分与单个“米”条目不匹配。

术语

我想这是一个非常常见的文本检索案例,但我不知道领域术语是什么。

代码

目前我正在从 SQL 查询中加载字典

tagList.Add(new KeyValuePair<string, string>(reader[0].ToString(), "0"));

然后通过循环字典然后循环通过 RTB 来搜索 RichTextBox。

foreach (KeyValuePair<string, string> word in tagList)
{
    int startindex = 0;
    while (startindex < richTextBox1.TextLength)
    {
        int wordstartIndex = richTextBox1.Find(word.Key, startindex, RichTextBoxFinds.WholeWord);
        if (wordstartIndex != -1)
        {
            Console.WriteLine("found: " + word.Key);

            richTextBox1.SelectionStart = wordstartIndex;
            richTextBox1.SelectionLength = word.Key.Length;
            if (word.Value.ToString() == "0")
            {
                richTextBox1.SelectionBackColor = Color.Yellow;
            }
        }
        else
            break;
        startindex += wordstartIndex + word.Key.Length;
    }
}

标签: c#information-retrieval

解决方案


我重构了我的查找数据库表,并为带有 1、2、3 和 4 个单词的标签制作了 4 列 - 例如“大米”、“米酒”、“米酒醋”和“酸米酒面”

我使用了 4 个字典,并使用数据库查找表中的相应列加载了每个字典。

我先用四词词典查看目标字符串,然后是三词词典,然后是二,然后是一词词典。

我使用 Regex 的整个单词边界模式 "\b" + word.key + "\b" 来标记单词。

慢,但它现在可以完成这项工作。

foreach (KeyValuePair<string, string> word in tagTwo)
{
    string ingredientString = richTextBox1.Text.ToLower();
    if (ingredientString.Contains(word.Key))
    {
        string input = ingredientString;
        string pattern = @"\b" + word.Key + "\\b";

        if (Regex.IsMatch(input, pattern) == true)
        {
            Console.WriteLine(pattern);
            string replace = "[[token]]";
            string output = Regex.Replace(input, pattern, replace);
            richTextBox1.Text = output;

            insertStringLine = "INSERT INTO ingredientCount (ingredientTag, tagCount) VALUES ('" + word.Key + "',1);" + Environment.NewLine;
            SQLiteCommand createSQL = new SQLiteCommand(insertStringLine.Replace(",)", ")"), conn);
            createSQL.ExecuteNonQuery();
        }
    }
}

推荐阅读