创建文件夹中每个文件内容的索引

Igg*_*ggY 2 python search

我正在用Python 制作一个搜索工具。

其目标是能够按内容搜索文件。(我们主要谈论源文件、文本文件,而不是图像/二进制文件 - 即使在元数据中搜索将是一个很大的改进)。目前我不使用正则表达式,随意的纯文本。

这部分算法效果很好!

问题是我意识到我主要在相同的几个文件夹中搜索,我想找到一种方法来构建文件夹中每个文件的内容的索引。并且能够尽快知道我正在搜索的句子是否在xxx.txt中或者是否不可能存在。目前的想法是为每个文件维护一个校验和,使我能够知道它是否包含特定字符串。

你知道有什么算法接近这个吗?

我不需要 100% 的成功率,我更喜欢小索引而不是 100% 成功的大索引。这个想法是提供一个通用工具。

编辑:为了清楚起见,我想搜索文件内容的一部分。因此,对其所有内容创建 md5 哈希值并将其与我正在搜索的内容的哈希值进行比较并不是一个好主意;)

nam*_*mit 6

这里我使用 whoosh lib 进行搜索/索引..上部是索引文件,下部是演示搜索..

#indexing part

from whoosh.index import create_in
from whoosh.fields import *
import os
import stat
import time

schema = Schema(FileName=TEXT(stored=True), FilePath=TEXT(stored=True), Size=TEXT(stored=True), LastModified=TEXT(stored=True),
                LastAccessed=TEXT(stored=True), CreationTime=TEXT(stored=True), Mode=TEXT(stored=True))

ix = create_in("./my_whoosh_index_dir", schema)
writer = ix.writer()



for top, dirs, files in os.walk('./my_test_dir'):
    for nm in files:
        fileStats = os.stat(os.path.join(top, nm))
        fileInfo = {
            'FileName':nm,
            'FilePath':os.path.join(top, nm),
            'Size' : fileStats [ stat.ST_SIZE ],
            'LastModified' : time.ctime ( fileStats [ stat.ST_MTIME ] ),
            'LastAccessed' : time.ctime ( fileStats [ stat.ST_ATIME ] ),
            'CreationTime' : time.ctime ( fileStats [ stat.ST_CTIME ] ),
            'Mode' : fileStats [ stat.ST_MODE ]
        }
        writer.add_document(FileName=u'%s'%fileInfo['FileName'],FilePath=u'%s'%fileInfo['FilePath'],Size=u'%s'%fileInfo['Size'],LastModified=u'%s'%fileInfo['LastModified'],LastAccessed=u'%s'%fileInfo['LastAccessed'],CreationTime=u'%s'%fileInfo['CreationTime'],Mode=u'%s'%fileInfo['Mode'])

writer.commit()


## now the seaching part
from whoosh.qparser import QueryParser
with ix.searcher() as searcher:
    query = QueryParser("FileName", ix.schema).parse(u"hsbc") ## look for files with 'hsbc' in their name
    results = searcher.search(query)
    for x in results:
        print x['FileName']
Run Code Online (Sandbox Code Playgroud)