我有一个名为“pads”的文件夹,我在其中创建了6个记事本文档(1.txt,2.txt..等等..6.txt),我试图执行下面的代码,并得到以下错误
import os
from whoosh.index import create_in
from whoosh.fields import Schema, TEXT, ID
import sys
from whoosh.qparser import QueryParser
from whoosh import scoring
from whoosh.index import open_dir
def createSearchableData(root):
'''
Schema definition: title(name of file), path(as ID), content(indexed but not stored),textdata (stored text content)
'''
schema = Schema(title=TEXT(stored=True),path=ID(stored=True),\
content=TEXT,textdata=TEXT(stored=True))
if not os.path.exists("indexdir"):
os.mkdir("indexdir")
# Creating a index writer to add document as per schema
ix = create_in("indexdir",schema)
writer = ix.writer()
filepaths = [os.path.join(root,i) for i in os.listdir(root)]
for path in filepaths:
fp = open(path,'r')
print(path)
text = fp.read()
writer.add_document(title=path.split("\\")[1], path=path,\
content=text,textdata=text)
fp.close()
writer.commit()
root = "pads"
createSearchableData(root)
###ERROR###
pads/5.txt
IndexError: list index out of range
为什么它要读取一个记事本文档,它是5.txt文件,而不是其他文件?你知道吗
首先,确保文件中的所有路径都包含“\\”。另外,如果您想获得文档的标题,我建议您使用split()函数获得的向量的最后一个位置。它将是如下所示:
writer.add_document(title=path.split("\\")[1], path=path,
根据打印的路径,路径中没有反斜杠。Split返回一个单元素数组,python数组从0开始。你知道吗
相关问题 更多 >
编程相关推荐