Home > Mobile >  How to return certain text in a file, python - New to programming
How to return certain text in a file, python - New to programming

Time:05-28

I have two text files: File1.txt:

random words random words

*** BEGINNING AT ***

Need these words

*** ENDING AT ***

more random words

file2.txt:

random words random words

more random words *** BEGINNING AT ***

Don't need these words

*** BEGINNING AT ***

Need these words here

*** ENDING AT ***

These words should be ignored

I so far have developed this function:

import re

"""function that returns a list of lower case words that are within the region of interest"""

def get_certain_words_from_file(filename):

"""defines the given region and returns a list of words inside"""

with open(filename, 'r') as file:
    lines = file.read()
    list_of_lines = lines.splitlines()
    index_start = 0
    index_end = 0
    for i in range(len(list_of_lines)):
        if list_of_lines[i].startswith('***BEGINNING AT '):
            index_start  = i
        if list_of_lines[i].startswith('*** ENDING AT'):
            index_end  = i
    valid_lines = list_of_lines[index_start : index_end] 
    valid_lines = "".join(str(x) for x in valid_lines)
    valid_lines = valid_lines.lower()
    valid_lines = valid_lines.split()
    
    valid_words = []
    words_on_line = []
    for line in valid_lines:
        words_on_line = re.findall("[a-z] [-'][a-z] |[a-z] [']?|[a-z] ", line)
    for word in words_on_line:
        valid_words.append(word)
    return valid_words
            

filename = "file2.txt"

words = get_words_from_file(filename)

print(filename, "loaded ok.")

print("{} valid words found.".format(len(words)))

print("Valid word list:")

for word in words:

print(word)

the current output is:

file2.txt loaded ok.

0 valid words found.

Valid word list:

But I'm trying to get:

file2.txt loaded ok.

4 valid words found.

Valid word list:

need

these

words

here

My thinking is its something wrong with the first section, but new to python and programming as a whole so not too sure

Anything would help thanks!

CodePudding user response:

from what I see - you don't need regex; you can use Python "in" keyword.

filename = 'input_file'
valid_words = ['word1', 'word2']

with open(filename, 'r') as file:
    lines = file.read()
    list_of_lines = lines.splitlines()
    lines_with_word = []
    for line in list_of_lines:
        for word in valid_words:
            if word in line:
                lines_with_word.append(line)
    print(lines_with_word)
  • Related