python - 检查数百万搜索查询中是否存在大量单词的有效方法
问题描述
- 我有一个包含 5000 万个搜索查询的字符串列表。[每个查询中 1-500 多个单词]。
- 我还有一个包含 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
]
解决方案
我建议FlashText,它被开发为非常有效地完成此类任务。只要您搜索的关键字是纯字符串(而不是复杂的正则表达式),它就会起作用。
推荐阅读
- php - PHP:file_get_contents 返回错误数据
- azure - 我可以将部署槽之类的东西用于 Azure 存储静态网站吗?
- cypress - 有没有办法在线运行赛普拉斯测试?
- php - 显示条码图像给字符是不允许的
- git - 如何限制仅从特定分支创建分支
- windows-xp - Delphi 6 TQuery 无法在一台 Windows XP 机器上修改只读数据集
- java - Jboss java.lang.OutOfMemoryError:Java 堆空间
- javascript - 如何将 webpack 哈希名称添加到服务工作者文件?
- c# - Xamarin.Forms FlexLayout 调整为最大值
- javascript - JavaScript:检查所有数组是否包含相同的值?