python - 如何查找一个单词是否在字符串中 - FAST,python

标签 python algorithm

<分区>

所以我想确定给定字符串中的单词。这些字符串是域名。我有大约 5000 个域名和 60000 个字典单词的字典要检查。这将导致每个域检查 60000 次,总计大约 300.000.000 次操作,这简直是疯狂。

因此我想问一下,是否有更聪明的方法来解决这个问题,让字符串中的单词仍然存在。

我尝试用一​​个简单的循环来完成它,但我想这需要一个更智能的解决方案来处理大量的支票。

dictionary_of_words = ["I", "Stack", "overflow", "like", etc]
AllDomains = ["stackoverflow.com", "iLikeStackoverflow.com", etc]

def in_dictionary(AllDomains):
    #Setting a new column
    AllDomains["dictionary"] = False
    AllDomains["words"] = None

    for i in range(len(AllDomains)):
        # Scan if the entire word is in the dictionary
        if AllDomains["domain"].str.strip(".nl").str.lower().iloc[i] in dictionary_of_words:
            AllDomains["dictionary"].iloc[i] = True
            print(AllDomains["domain"].iloc[i])

        # Scan which words there are in the domain
        else:
            for word in dictionary_of_words:
                print(word)
                if word in AllDomains["domain"].str.strip(".nl").str.lower().iloc[i]:
                    if AllDomains["words"].iloc[i] == None:
                        AllDomains["words"].iloc[i] = word
                    else:
                        AllDomains["words"].iloc[i] = AllDomains["words"].iloc[i] + f", {word}"

                    print(AllDomains["domain"].iloc[i])

    return AllDomains

最佳答案

  1. 将所有单词放在一个集合(而不是列表)中,这样您就可以非常快速地检查一个字符串,看它是否与任何单词匹配。
  2. 将所有长度的单词放在一个集合中。
  3. 对于每个长度,对于每个域名,获取该长度的所有子串,并检查它是否在单词集中。

由于您最终可能会得到大约 10 个长度,而大多数域的长度将少于 20 个字符,因此这将导致每个域名仅进行几百次快速检查。

关于python - 如何查找一个单词是否在字符串中 - FAST,python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58044209/

相关文章:

python - 人口必须是一个序列或集合。对于字典,使用 list(d)

python - Django,测试应用程序的行为

python - 在 Python 中散列文件

algorithm - 具有重复值的大型二叉树中两个值之间的最小距离

.net - 适用于大量数据的最佳抽取算法有哪些?

python - 更改 PyCharm 中的 reStructuredText 格式以自动生成注释

python - 使用python将某些文件从一个文件夹复制到另一个文件夹

python - 有效地计算没有尾随零的阶乘?

algorithm - 将有序索引分配给二叉树

algorithm - 寻找最长的重复子串