在两个字符串中查找不同的单词

本文关键字:查找 单词 字符串 两个 | 更新日期: 2023-09-27 18:26:26

我有一大堆短语,比如

"Nola jumped off the cliff"
"Loroy jumped off the cliff"
"Nola jumped off the couch"
"Leroy lept off the couch"

我需要找到一个短语中不同单词的每个点,并将该单词添加到一个节点中,该节点是一个可以在短语中该位置使用的单词列表。所以我们最终会。

"Node1(1) Node2(1) off the Node3(1)"
"Node1(2) Node2(1) off the Node3(1)"
...etc

其中,节点1表示名称列表(诺拉、勒罗伊),节点2表示动作列表(跳跃、睡觉),节点3最终表示位置列表(悬崖、沙发)

这个想法是取一个短语列表,让它自动创建节点,并在其中填充短语中该节点可以使用的单词。

那么,第一,我该如何生成短语节点列表?我一直不知道如何比较两个句子,看看它们减去一个单词后是否完全一样。

第二,一旦我设置了节点,比较所有节点组合以获得新匹配的最佳方法是什么?(希望这是有意义的)

在两个字符串中查找不同的单词

不错,我喜欢它。因为你用C#标记了你的问题,所以我也用C#写了答案。

获取两个短语之间不同单词的快速方法:

string phrase1 = "Nola jumped off the cliff";
string phrase2 = "Juri jumped off the coach";
//Split phrases into word arrays
var phrase1Words = phrase1.Split(' ');
var phrase2Words = phrase2.Split(' ');
//Find the intersection of the two arrays (find the matching words)
var wordsInPhrase1and2 = phrase1Words.Intersect(phrase2Words);
//The number of words that differ 
int wordDelta = phrase1Words.Count() - wordsInPhrase1and2.Count();
//Find the differing words
var wordsOnlyInPhrase1 = phrase1Words.Except(wordsInPhrase1and2);
var wordsOnlyInPhrase2 = phrase2Words.Except(wordsInPhrase1and2);

您可以节省时间并使用内置的LINQ函数Intersect、Except等。

关于随机创建短语,请参阅NominSim的答案。

另一个基于Linq的解决方案,可以生成所有可能的组合:

var phrases = new List<string> {
           "Nola jumped off the cliff",
           "Loroy jumped off the cliff",
           "Nola jumped off the couch",
           "Leroy lept off the couch"
                           };
var sets = (from p in phrases
            from indexedWord in p.Split(' ').Select((word,idx) => new {idx,word})
            group indexedWord by indexedWord.idx into g
            select g.Select(e => e.word).Distinct()).ToArray();

var allCombos = from w1 in sets[0]
                from w2 in sets[1]
                from w3 in sets[2]
                from w4 in sets[3]
                from w5 in sets[4]
                select String.Format("{0} {1} {2} {3} {4}.", w1, w2, w3, w4, w5);

这不是最可读的代码,但写起来很有趣

首先要生成列表,应该这样做:

        HashSet<String>[] NodeList = new HashSet<String>[phraseLength];
        for (int i = 0; i < phraseLength; i++)
        {
            NodeList[i] = new HashSet<string>();
        }
        foreach (String phrase in PhraseList)
        {
            string[] phraseStrings = phrase.Split(' ');
            for (int i = 0; i < phraseLength; i++)
            {
                if(!NodeList[i].Contains(phraseStrings[i]))
                {
                    NodeList[i].Add(phraseStrings[i]);
                }
            }
        }

然后,当你创建句子时,你可以简单地遍历NodeList,并从每个节点中选择一个String,如果你想随机地这样做,可能是这样的:

        String sentence = "";
        foreach (HashSet<String> Node in NodeList)
        {
            Random rand = new Random();
            sentence += Node.ToArray()[rand.Next(0, Node.Count)];
        }

需要注意的是,如果您需要随机访问HashSet,那么它可能不是最好的主意。