【问题标题】:Given a list of words and a sentence find all words that appear in the sentence either in whole or as a substring给定一个单词列表和一个句子,找到句子中出现的所有单词,无论是整体还是作为子字符串
【发布时间】:2023-08-30 02:21:01
【问题描述】:

问题

给定一个字符串列表,从列表中找出给定文本中出现的字符串。

示例

list = ['red', 'hello', 'how are you', 'hey', 'deployed']
text = 'hello, This is shared right? how are you doing tonight'
result = ['red', 'how are you', 'hello']

'red' 因为它有 'shared' 有 'red' 作为子字符串

  • 这与this question 非常相似,只是我们需要查找的单词也可以是子字符串。
  • 该列表非常大,并且会随着用户的增加而增加,而不是整个长度几乎相同的文本。
  • 我正在考虑一个解决方案,其中时间复杂度取决于文本长度而不是单词列表,以便即使添加大量用户也可以扩展。

解决方案

  • 我从给出的单词列表中构建了一个 trie
  • 对文本运行 dfs 并根据 trie 检查当前单词

伪代码

def FindWord (trie, text, word_so_far, index):
    index > len(text)
        return
    //Check if the word_so_far is a prefix of a key; if not return
    if trie.has_subtrie(word) == false:
       return 
    //Check if the word_so_far is a key; if ye add to result and look further 
    if trie.has_key(word) == false:
        // Add to result and continue
    //extend the current word we are searching
    FindWord (trie, text, word_so_far + text[index], index + 1)
    //start new from the next index 
    FindWord (trie, text, "", index + 1)

问题在于,虽然运行时现在取决于 len(text),但它在构建 trie 后以时间复杂度 O(2^n) 运行,这对于多个文本来说是一次性的,所以没问题。

我没有看到任何重叠的子问题来记忆和改进运行时。

您能否建议任何方法我可以实现依赖于给定文本的运行时,而不是可以按每个处理和缓存的单词列表,并且也比这更快。

【问题讨论】:

  • 你试过什么?您有自己的工作代码示例吗?
  • 我已经发布了我所做的伪代码。实际代码有很多不相关的部分,可能会分散实际问题的注意力
  • @JordanSinger OP 已经对他的尝试给出了合理的信息描述,因此无需发布实际代码,因为实际问题在于 算法
  • 您多久从同一索引处的“”递归重新启动? (或者以其他方式重复之前的起点,需要大量工作重做)也许根据元组键(word_so_far,index)创建一个计数器,看看是否发生这种情况。

标签: python algorithm search trie


【解决方案1】:

扩展@David Eisenstat 建议以使用 aho-corasick 的算法来实现这一点。我找到了一个简单的 python 模块(pyahocorasic) 可以做到这一点。

这是问题中给出的示例的代码外观。

import ahocorasick

def find_words(list_words, text):
    A = ahocorasick.Automaton()

    for key in list_words:
      A.add_word(key, key)

    A.make_automaton()

    result = []
    for end_index, original_value in A.iter(text):
      result.append(original_value)

    return result

list_words = ['red', 'hello', 'how are you', 'hey', 'deployed']
text = 'hello, This is shared right? how are you doing tonight'
print(find_words(list_words, text))

Or run it online

【讨论】:

    【解决方案2】:

    您尝试做的理论上合理的版本称为Aho--Corasick。实现后缀链接有点复杂 IIRC,所以这里有一个只使用 trie 的算法。

    我们一个字母一个字母地使用文本。在任何时候,我们都会在 trie 中维护一组可以遍历的节点。最初,该集合仅包含根节点。对于每个字母,我们遍历集合中的节点,如果可能的话,通过新字母下降。如果结果节点是匹配的,很好,报告它。无论如何,把它放在下一组。下一组也包含根节点,因为我们可以随时开始新的匹配。

    这是我在 Python 中快速实现的尝试(未经测试,无保修等)。

    class Trie:
        def __init__(self):
            self.is_needle = False
            self._children = {}
    
        def find(self, text):
            node = self
            for c in text:
                node = node._children.get(c)
                if node is None:
                    break
            return node
    
        def insert(self, needle):
            node = self
            for c in needle:
                node = node._children.setdefault(c, Trie())
            node.is_needle = True
    
    
    def count_matches(needles, text):
        root = Trie()
        for needle in needles:
            root.insert(needle)
        nodes = [root]
        count = 0
        for c in text:
            next_nodes = [root]
            for node in nodes:
                next_node = node.find(c)
                if next_node is not None:
                    count += next_node.is_needle
                    next_nodes.append(next_node)
            nodes = next_nodes
        return count
    
    
    print(
        count_matches(['red', 'hello', 'how are you', 'hey', 'deployed'],
                      'hello, This is shared right? how are you doing tonight'))
    

    【讨论】:

    • 基于 Trie 的解决方案的最坏情况时间复杂度是多少。有n^2 子串,每个找到每个子串都是 trie 中的线性时间。那么O(n^3)?
    • @thebenman 你有一个带有 a、aa、aaa、aaaa 等的简并特里树,但这只会将它推到特里树的大小乘以文本大小(二次)。
    【解决方案3】:

    如果您的目标是依赖于文本窗口的更快代码,您可以使用集合查找来加快速度。如果可行,请将查找列表改为一个集合,然后在文本中查找所有可能的窗口以用于查找。

    def getAllWindows(L):
        tracker = set()
        for w in range(1, len(L)+1):
            for i in range(len(L)-w+1):
                sub_window = L[i:i+w]
                if sub_window not in tracker:
                    tracker.add(sub_window)
                    yield sub_window
    
    
    lookup_list = ['red', 'hello', 'how are you', 'hey', 'deployed']
    lookup_set = set(lookup_list)
    text = 'hello, This is shared right? how are you doing tonight'
    result = [sub_window for sub_window in getAllWindows(text) if sub_window in lookup_list]
    print(result)
    #Output:
    ['red', 'hello', 'how are you']
    

    【讨论】: