Skip to content Skip to sidebar Skip to footer

Searching A Text File And Printing Line Numbers

How do you get your function to find the lines in the text file where the word occurs and print the corresponding line numbers? I had to open a text file with the paragraph and the

Solution 1:

Use enumerate and a set union of the line in question if you just want to test for presence of individual words:

words={'some', 'target', 'words', 'in', 'a', 'set'}

withopen(f_name) as fin:
    for line_num, line in enuemrate(fin):
        ifset(line.split()) & words:
            print(line_num, line)

Solution 2:

try this:

words = []
lines = {}
for i in words:
    lines[i] = []

with open("file", "r") as fin:
    curLine = 0for i in fin.readLines():
        for j in words:
            if j in i:
                lines[j].append(curLine)
        curLine += 1for i in words:
    printlines[j]

Post a Comment for "Searching A Text File And Printing Line Numbers"