【发布时间】:2017-02-06 13:57:25
【问题描述】:
问题:
我想通过在 python 中创建一个数据结构来执行索引,该结构将存储给定文本文件中的所有单词,还将存储其行号(这些单词出现的所有行)以及单词的位置(第 # 列)在该特定行中。
到目前为止,我可以通过将所有行号附加到列表中来将单词存储在字典中,但我无法将它们的位置存储在该特定行中。
我需要这个数据结构来更快地搜索文本文件。
这是我到目前为止的代码:
from collections import defaultdict
thetextfile = open('file.txt','r')
thetextfile = thetextfile.read()
file_s = thetextfile.split("\n")
wordlist = defaultdict(list)
lineNumber = 0
for (i,line) in enumerate(file_s):
lineNumber = i
for word in line.split(" "):
wordlist[word].append(lineNumber)
print(wordlist)
【问题讨论】:
-
你的文本文件是什么格式的?
-
@Leonid ,可以是任何格式。
-
@EdwinvanMierlo ,我是 python 新手,我不能很好地进行。
-
@KiaraSingh , stackoverflow.com/help/how-to-ask
-
编辑了我的问题,我想现在应该很清楚了。
标签: python python-3.x indexing