Creating a dictionary with line numbers

I am trying to read txt.file and print the line numbers in which the keywords appear. This is what I have so far:

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)

Output:

>>>{'mortal': 30, 'demon': 122, 'dying': 9, 'ghastly': 82, 'evil': 106, 'raven': 120, 'ghost': 9}

The above result is somewhat correct. The problem I am experiencing, for example, a crow should print 44, 53, 55, 64, 78, 97, 104, 111, 118, 120 is not only the number of the last line (120) in which it appeared.

I have been working on this issue for a solid day, and I'm not sure how to add all the line numbers in which the keyword is displayed without overwriting the already saved line number in the dictionary.

I am new to Python, so if this is something simple that I'm missing, I apologize and any advice would be greatly appreciated.

+4
source share
2

, 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)
+3

defaultdict, . - :

from collections import defaultdict

def index(filename, word_lst):
    d = defaultdict(list)

    with open(filename) as f:
        for lineno, line in enumerate(f):
            for word in words:
                if word in line:
                    d[word].append(lineno)
0

Source: https://habr.com/ru/post/1615932/


All Articles