【问题标题】:How to calculate possible word subsequences matching a pattern?如何计算匹配模式的可能单词子序列?
【发布时间】:2014-02-18 23:21:51
【问题描述】:

假设我有一个序列:

    Seq = 'hello my name'

还有一个字符串:

    Str = 'hello hello my friend, my awesome name is John, oh my god!'

然后我在字符串中查找我的序列的匹配项,因此我为单元格数组中序列的每个单词获取每个匹配项的“单词”索引,因此第一个元素是包含匹配项的单元格hello',第二个元素包含匹配 'my' 和第三个匹配 'name'。

    Match = {[1 2];      %'hello' matches
             [3 5 11];   %'my' matches
             [7]}        %'name' matches

我需要代码以某种方式得到一个答案,说明可能的子序列匹配是:

    Answer = [1 3 7;     %[hello my name]
              1 5 7;     %[hello my name]
              2 3 7;     %[hello my name]
              2 5 7;]    %[hello my name]

以这样一种方式,“答案”包含所有可能的有序序列(这就是为什么 my(word 11) 永远不会出现在“答案”中,位置 11 之后必须有一个“名称”匹配。

注意:“Seq”的长度和匹配数可能会有所不同。

【问题讨论】:

    标签: matlab word sequence distance


    【解决方案1】:

    由于Matches的长度可能会有所不同,您需要使用comma-separated listsndgrid一起生成所有组合(方法与this other answer中使用的方法类似)。然后过滤掉索引不增加的组合,使用difflogical indexing

    cc = cell(1,numel(Match)); %// pre-shape to be used for ndgrid output
    [cc{end:-1:1}] = ndgrid(Match{end:-1:1}); %// output is a comma-separated list
    cc = cellfun(@(v) v(:), cc, 'uni', 0) %// linearize each cell
    combs = [cc{:}]; %// concatenate into a matrix
    ind = all(diff(combs.')>0); %'// index of wanted combinations
    combs = combs(ind,:); %// remove unwanted combinations
    

    所需的结果在变量combs 中。在你的例子中,

    combs =
         1     3     7
         1     5     7
         2     3     7
         2     5     7
    

    【讨论】:

    • 非常感谢,它运行良好!我不知道 ndgrid 和 cellfun 函数,仍然必须了解它是如何工作的,因为这两个步骤对我来说并不清楚,但我会自己调查。谢谢你,先生!
    • @ACenTe25 调查后随时询问是否需要 :-)
    • 我想我现在明白了。即使我写了[cc{1:end}] = ndgrid(Match{1:end});,我也能得到类似的结果,对吧?如果我理解正确的话,唯一的变化是在combs 中提供组合的顺序。
    • @ACenTe25 没错。这样做的唯一目的是获得与您的问题相同的顺序。当然,您可以将 [cc{1:end}] = ndgrid(Match{1:end}); 缩写为 [cc{:}] = ndgrid(Match{:});
    猜你喜欢
    • 1970-01-01
    • 2022-06-21
    • 2016-04-15
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多