我试图通读一个txt.file并打印关键字出现的行号.这是我到目前为止所拥有的:
def index(filename, word_lst):
dic = {}
line_count = 0
for word in word_lst:
dic[word] = 0
with open(filename) as infile:
for line in infile:
line_count += 1
for word in word_lst:
if word in line:
dic[word] = line_count
print(dic)
输出:
>>>{'mortal': 30, 'demon': 122, 'dying': 9, 'ghastly': 82, 'evil': 106, 'raven': 120, 'ghost': 9}
以上输出有点正确.我遇到的问题是,例如,乌鸦应该打印44,53,55,64,78,97,104,111,118,120,而不仅仅是它出现的最后一个行号(120).
我一直在努力解决这个问题,并且我不确定如何添加关键字出现的所有行号而不覆盖字典中已存储的行号.
我是Python的新手,所以如果它是一个简单的我想念我道歉,任何提示将不胜感激.
解决方法:
要从单词映射多个行号,您需要映射到列表,而不是int:
def index(filename, word_lst):
dic = {}
line_count = 0
for word in word_lst:
dic[word] = [] #
with open(filename) as infile:
for line in infile:
line_count += 1
for word in word_lst:
if word in line:
dic[word].append(line_count) #
print(dic)
标签:python,dictionary