我需要一个问题的帮助,我在其中创建一个名为index()的函数,该函数将文件作为字符串和单词列表。程序将找到每个单词所在的数字行,并返回单词旁边的数字行。
到目前为止,我的代码读作:
f=open(file,'r')
read = f.readlines()
for word in lst:
if word in range(len(read)):
word[:]+1
return read
我相当坚持,但我认为你应该搜索readlines列表的索引()。对于这个问题,我必须使用for循环和格式。任何人都可以帮助我吗?
对于FYI,回报将如下所示:
index('raven.txt',['raven','mortal','dying','ghost','ghastly','evil','demon])
ghost 9
dying 9
demon 122
evil 99, 106
ghastly 82
mortal 30
raven 44, 53, 55, 64, 78, 97, 104, 111, 118, 120
我也在使用python 3。
答案 0 :(得分:0)
def index(file, wordList):
word_dict = dict()
for word in wordList:
word_dict[word] = list()
with open(file,'r') as f:
for lineNum, lines in enumerate(f,1):
for word in wordList:
if word in lines:
word_dict[word].append(lineNum)
return word_dict
myWordDict = index('raven.txt',['raven','mortal','dying','ghost','ghastly','evil','demon'])
for items in myWordDict:
print(items, ":", myWordDict[items])
这是你想要的吗?