python为txt文件加入索引
时间: 2024-05-02 13:23:25 浏览: 14
要为一个txt文件添加索引,可以使用Python中的第三方库Whoosh。下面是一个简单的例子,演示如何使用Whoosh为文本文件添加索引:
```python
import os
from whoosh.index import create_in
from whoosh.fields import *
from whoosh.qparser import QueryParser
# 定义索引保存目录和文本文件路径
indexdir = "indexdir"
txtpath = "test.txt"
# 删除已存在的索引保存目录
if os.path.exists(indexdir):
for filename in os.listdir(indexdir):
os.remove(os.path.join(indexdir, filename))
os.rmdir(indexdir)
# 创建索引保存目录和Schema
os.mkdir(indexdir)
schema = Schema(path=ID(stored=True), content=TEXT)
# 创建索引并打开writer
ix = create_in(indexdir, schema)
writer = ix.writer()
# 读取txt文件并为每行添加索引
with open(txtpath, "r", encoding="utf-8") as f:
for i, line in enumerate(f):
writer.add_document(path=str(i), content=line.strip())
# 提交并关闭writer
writer.commit()
# 打开searcher并执行查询
searcher = ix.searcher()
query = QueryParser("content", ix.schema).parse("hello")
results = searcher.search(query)
# 输出查询结果
for hit in results:
print(hit["path"])
```
以上代码将读取文本文件`test.txt`,并为其中每行内容添加一个索引,保存到指定的索引保存目录中。然后可以使用查询语句在索引中搜索匹配的内容。这里的查询语句是搜索包含单词"hello"的行,并输出匹配行的行号。