创建包含关键字行号的字典

P.H*_*.HW 5 python dictionary

我正在尝试读取 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)
Run Code Online (Sandbox Code Playgroud)

输出:

>>>{'mortal': 30, 'demon': 122, 'dying': 9, 'ghastly': 82, 'evil': 106, 'raven': 120, 'ghost': 9}
Run Code Online (Sandbox Code Playgroud)

上面的输出有些正确。我遇到的问题是,例如,raven 应该打印 44, 53, 55, 64, 78, 97, 104, 111, 118, 120 而不仅仅是它出现的最后一个行号 (120)。

我已经花了整整一天的时间来解决这个问题,我不知道如何添加关键字出现的所有行号而不覆盖字典中已存储的行号。

我是Python新手,所以如果我错过了一些简单的东西,我深表歉意,任何提示将不胜感激。

fal*_*tru 3

要从单词映射多个行号,您需要映射到list, 而不是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)
Run Code Online (Sandbox Code Playgroud)