【发布时间】:2015-11-14 20:46:24
【问题描述】:
您将实现函数 index(),它将文本文件的名称和单词列表作为输入。对于列表中的每个单词,您的函数将在文本文件中查找该单词出现的行并打印相应的行号(编号从 1 开始)。您应该只打开和读取一次文件。
我只能统计一次。
def index(filename, words):
infile = open(filename)
content = infile.readlines()
infile.close()
count = {}
for word in words:
if word in count:
count[word] += 1
else:
count[word] = 1
for word in count:
print('{:12}{},'.format(word, count[word]))
Output :index('raven.txt',['raven'])
raven 1,
Desired Output : index('raven.txt',['raven'])
raven 44, 53, 55, 64, 78, 97, 104, 111, 118, 12(No of lines it appear)
【问题讨论】:
-
你在第二个for循环中重新定义
word... -
不,我不会实现函数
index()。你不能告诉我该怎么做。