我有可能会是这样一个文本文件,图书索引...Python中创建的文本文件
3:degree
54:connected
93:adjacent
54:vertex
19:edge
64:neighbor
72:path
55:shortest path
127:tree
3:degree
55:graph
64:adjacent and so on....
我希望有我的函数read每一行文本,并在结肠分裂它做它变成一个字典,其中的单词处于“关键”位置,并且页码处于字典的“值”位置 - 然后我必须创建一个新的字典并扫描每个单词,如果它已经在字典中只需在页面后面添加页码,如果它不在字典中,我会将它添加到字典中。
这是到目前为止我的想法......
def index(fileName):
inFile=open(fileName,'r')
index={}
for line in inFile:
line=line.strip() #This will get rid of my new line character
word=line[1]
if word not in index:
index[word]=[]
index[word].append(line)
return index
fileName='terms.txt'
print(index(fileName))
我在正确的页面上,但只需要一点点帮助,走了。
你有没有看这个,HTTP://stackoverflow.com/questions/3199171/append-multiple-values-for-one-key-在-python的词典?方法相似。 – AppliedNumbers