Dani DcTurner
Dani DcTurner

Reputation: 83

How to find a word in a text file and print another that is in the next line in Python

I have a text file full of text where every time a certain word appears in one line, the next line is a number that I want to print in another text file. I have been using enumerate to find the number NEXT to the word, but I'd like the one in the following line. For example, this is the text file:

Line 1: Hello bye
Line 2: 23
Line 3: Adios bye
Line 4: 45

I'd like the program to find the word bye and print 23 and 45. Right now I can only find Hello and print bye. How do I make it print the following line? Thank you.

Upvotes: 0

Views: 1975

Answers (1)

Corsaka
Corsaka

Reputation: 422

You can search each line, then move to the next line, like so:

with open('text.txt','r') as f:
    for line in f:
        phrase = 'bye'
        if phrase in line: #if the phrase is present
            next(f) #move to next line

You can do whatever you want with the lines following this; if you're trying to find a number, you could use .isdigit() assuming the line only contains numbers.

A possible alternate solution is to use regular expressions:

import re

def hasNumber(string):
    return bool(re.search(r'\d', string)) #returns true/false

with open('text.txt','r') as f:
    for line in f:
        if re.match('bye',line): #if it contains the word "bye"
            newline = next(f) #declare the next line
            if hasNumber(newline): #if that line contains any numbers
                number = re.compile(r'\d') #find those numbers
                print(''.join(number.findall(newline)[:])) #print those numbers

The re.match function returns true if the second variable matches the first (though this isn't strictly true, as it only acts this way with conditionals).

Upvotes: 1

Related Questions