通过读取已建好的全文索引,对文件夹下的中文文本进行检索,可以使用布尔运算符AND、OR、NOT,输入检索词后返回检索词所在的文件名与其所在的文件夹
时间: 2024-05-04 15:18:19 浏览: 18
实现上述功能,可以使用Python的第三方库Whoosh来进行全文检索。以下是一个示例代码:
```python
from whoosh.index import create_in, open_dir
from whoosh.fields import *
from whoosh.qparser import QueryParser
# 创建或打开索引
schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT)
indexdir = "/path/to/indexdir"
if not os.path.exists(indexdir):
os.mkdir(indexdir)
ix = create_in(indexdir, schema)
#ix = open_dir(indexdir)
# 往索引中添加文件
def add_doc(folder, filename, content):
writer = ix.writer()
writer.add_document(title=filename, path=os.path.join(folder, filename), content=content)
writer.commit()
# 检索函数
def search(query_str):
with ix.searcher() as searcher:
query = QueryParser("content", ix.schema).parse(query_str)
results = searcher.search(query)
for hit in results:
print("文件名:{}\n所在文件夹:{}\n".format(hit["title"], os.path.dirname(hit["path"])))
# 往索引中添加文件夹下的所有文件
def index_folder(folder):
for root, dirs, files in os.walk(folder):
for filename in files:
with open(os.path.join(root, filename), "r", encoding="utf-8") as f:
content = f.read()
add_doc(root, filename, content)
# 示例用法
folder = "/path/to/folder"
index_folder(folder)
search("检索词1 AND 检索词2 OR 检索词3 NOT 检索词4")
```
需要注意的是,Whoosh默认是不支持中文分词的,如果需要支持中文检索,需要使用第三方库jieba来进行中文分词。同时,对于大规模的文件夹,建立索引时可能需要较长的时间,可以考虑使用多线程或分布式来加速索引的建立。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)