我必须编写一个程序来读取名为" terms.txt"的文本文件。然后对文件进行排序并首先打印参考,然后是页码。这就是文件的样子:
3:degree
54:connected
93:adjacent
54:vertex
19:edge
64:neighbor
72:path
55:shortest path
127:tree
99:spanning tree
19:path
28:connected
3:degree
55:graph
64:adjacent
44:breadth first search
77:neighbor
55:degree
55:depth first search
19:degree
27:neighbor
16:Spanning Tree
这是运行程序后应该是的样子:
adjacent, 64, 93
breadth first search, 44
connected, 28, 54
degree, 3, 19, 55
depth first search, 55
edge, 19
graph, 55
neighbor, 27, 64, 77
path, 19, 72
shortest path, 55
spanning tree, 16, 99
tree, 127
vertex, 54
现在,这就是我所拥有的,它只是打印一个页码列表和一个参考列表......我不确定从哪里开始。一切都会有所帮助!
def bookIndex2():
indexList = []
pageNum = []
file = open('terms.txt', 'r')
for line in file:
pageNumber, reference = line.split(':')
pageNum.append(pageNumber)
indexList.append(reference)
indexList.sort()
print(pageNum)
print(indexList)
答案 0 :(得分:1)
您基本上需要使用将引用映射到页码列表的字典。在迭代文件时,将页码添加到该引用的列表中。处理完整个文件后,排序并打印字典的项目。我建议使用collections.defaultdict
而不是标准字典,因为这可以很好地构建列表字典。
from collections import defaultdict
index = defaultdict(list)
with open('terms.txt') as f:
for line in f:
page, reference = line.strip().lower().split(':')
index[reference].append(int(page))
for reference, pages in sorted(index.items()):
print "{}, {}".format(reference, ', '.join(str(i) for i in sorted(pages)))
答案 1 :(得分:0)
您的结果看起来像字典的内容,其中键是术语,值是页码列表。想法是:对于每行输入,将该页码添加到该术语的列表中(如果需要,创建条目/列表)。一个字典填满,只需通过键,以产生所需的输出。
答案 2 :(得分:0)
这可能会有所帮助。
from collections import defaultdict
def bookIndex2():
file = open('terms.txt', 'r')
occurance_dict = defaultdict(list)
for line in file:
pageNumber, reference = line.split(':')
occurance_dict[reference].append(pageNumber)
for term, occurances in sorted(occurance_dict.items()):
print [term]+[occurances]
答案 3 :(得分:0)
这是非常困难的家庭作业......
from collections import defaultdict
def bookIndex2():
file = open('terms.txt', 'r')
d = defaultdict(set)
for line in file:
num, name = line.strip().split(":")
d[name.lower()].add(num)
print "\n".join(map(", ".join, [[name] + sorted(num, key=int) for name, num in sorted(d.items())]))
输出:
adjacent, 64, 93
breadth first search, 44
connected, 28, 54
degree, 3, 19, 55
depth first search, 55
edge, 19
graph, 55
neighbor, 27, 64, 77
path, 19, 72
shortest path, 55
spanning tree, 16, 99
tree, 127
vertex, 54
答案 4 :(得分:0)
如果您正在寻找更简单/更容易理解的内容,这可能会有所帮助:)
def bookIndex2():
appendix = {}
file = open('terms.txt', 'r')
for line in file:
pageNumber, reference = line.split(':')
reference = reference.rstrip() "removes \n characters"
if reference in appendix:
appendix[reference]=appendix[reference]+', '+pageNumber
else:
appendix.update({reference : pageNumber})
print appendix
上面的代码将引用存储为字典中的键。如果引用已存在,则页码仅使用逗号附加到现有引用。