【问题标题】:Searching for indexes of multiple subtrings in multiple files在多个文件中搜索多个子字符串的索引
【发布时间】:2017-08-02 19:31:30
【问题描述】:

我有两个数据框,如下所示:

df1 : contains one variable ['search_term'] and 100000 rows 

这些是我想在我的文件中搜索的单词/短语

df2: contains parsed file contents in a column called file_text

此数据框中有 20000 行和两列 ['file_name', 'file_text']

我需要的是file_text中搜索词每次出现的索引。

我无法找到执行此搜索的有效方法。

我将 str.find() 函数与 groupby 一起使用,但每个 file_text-search 词大约需要 0.25 秒(对于 20k 个文件*100k 个搜索词,这会变得非常长)

任何关于如何以快速有效的方式做到这一点的想法都将成为救命稻草!

【问题讨论】:

  • 将您的问题简化为具有输入和预期输出的代表性示例。基本上,看看如何提供minimal reproducible example
  • 如果您有工作代码并且想要改进它,您将有更好的机会:codereview.stackexchange.com
  • dataframe 是什么意思?我从来没有听说过这样的事情。
  • 如果您正在寻找完全匹配,请考虑en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm
  • re 引擎已经做了非常类似于 aho-corasick 的事情。事实上,我们确实尝试过,但并没有超过 re.finditer

标签: python string algorithm search


【解决方案1】:

我记得在我们的一个项目中不得不做类似的事情。我们有一组非常大的关键字,我们想在一个大字符串中搜索它们并找到这些关键字的所有出现。让我们在content 中调用我们要搜索的字符串。经过一些基准测试,我采用的解决方案是两遍方法:首先使用高度优化的in 运算符检查content 中是否存在关键字,然后使用正则表达式查找所有出现的关键字。

import re

keywords = [...list of your keywords ...]
found_keywords = []

for keyword in keywords:
    if keyword in content:
        found_keywords.append(keyword)

for keyword in found_keywords:
    for match in re.finditer(keyword, content):
        print(match.start())

【讨论】:

    猜你喜欢
    • 2011-04-28
    • 2021-11-04
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 2012-10-15
    相关资源
    最近更新 更多