I want to scan a .txt file line-by-line for specific words. When the words are found, I want to add that particular line into a list. Any help would be appreciated!

The code below prints an empty list...

list = [ ]
word = 'help!'

with open('help!') as f:
    lines = f.readlines()

if word in lines:
    list.append(word)

print(list)

3 Answers

2
Andry On

You can iterate over all lines in .txt file and check whether the word occurs in that line. If so, append that line to your list.

list = [ ]
word = 'help!'

with open('text_file.txt') as f:
    lines = f.readlines()

for line in lines: #iterate over lines
    if word in line: #check if word in line
        list.append(line) #add line

print(list)
0
Community On

You'd most likely want to do a for loop on the file for each line and see if your word shows up.

# declare variables
list = []
word = 'help!'

# filepath to your .txt file, if its in the
# same directory as your py script, then just set it as the .txt name
filePath = 'stackOverflow.txt'

# for each line in your .txt file
for line in open(filePath):
     # if your word is in that line then ... 
     if(word in line):
          # append to list
          list.append(line)

# print list
print(list)

Hope this helps! =)

0
Ethan On

You may want to be careful with checking a sentence for a word using:

If (word in line):
    list.append(line)

If word = “in” the above condition will return a false positive “True” when tested on the line “Sitting on the bench”.

A better approach maybe:

if (word in line.split(“ “)):
    list.append(line)

This will miss words that are followed by punctuation, so stripping the punctuation first would be an even better solution. You could import re and use a regular expression to remove punctuation first.

Regex = re.compile(r”\W+”)
if (word in Regex.sub(“ “,line).split(“ “)):
        list.append(line)