首页 > 解决方案 > 检查数百万搜索查询中是否存在大量单词的有效方法

问题描述

  1. 我有一个包含 5000 万个搜索查询的字符串列表。[每个查询中 1-500 多个单词]。
  2. 我还有一个包含 500 个单词和短语的字符串列表,我需要返回包含任何单词或短语 (2) 的搜索查询 (1) 的索引。

目标是只保留与某个主题(电影)相关的查询,然后使用 NLP 对这些过滤后的查询进行聚类(stemming -> tf_idf -> pca -> kmeans)。

我尝试使用嵌套循环过滤查询,但需要 10 多个小时才能完成。

filtered = []
with open('search_logs.txt', 'r', encoding='utf-8') as f:
    for i, line in enumerate(f):
        query, timestamp = line.strip().split('\t')
        for word in key_words:
            if word in query:
                filtered.append(i)

我研究了使用正则表达式(word1|word2|...|wordN)的解决方案,但问题是我无法将查询组合成一个大字符串,因为我需要过滤不相关的查询。

更新:日志和关键字的示例

search_logs.txt
'query  timestamp\n'
'the dark knight    2019-02-17 19:05:12\n'
'how to do a barrel roll    2019-02-17 19:05:13\n'
'watch movies   2019-02-17 19:05:13\n'
'porn   2019-02-17 19:05:13\n'
'news   2019-02-17 19:05:14\n'
'rami malek 2019-02-17 19:05:14\n'
'Traceback (most recent call last): File "t.py" 2019-02-17 19:05:15\n'
.......... # millions of other search queries
key_words = [
    'movie',
    'movies',
    'cinema',
    'oscar',
    'oscars',
    'george lucas',
    'ben affleck',
    'netflix',
    .... # hundreds of other words and phrases
]

标签: pythonregexnlp

解决方案


我建议FlashText,它被开发为非常有效地完成此类任务。只要您搜索的关键字是纯字符串(而不是复杂的正则表达式),它就会起作用。


推荐阅读