Michael Muscle
Michael Muscle

Reputation: 25

How to search within a text file from a users input than print it using python?

I am having troubles trying to read multiple lines within a text file using python. My issue is, taking a users specific input and finding that piece of text and printing it out with multiple lines following it. I am trying to keep this within a while function by using elif to continue this part. This code is to take a users U.S State that was inputted and print that state following with the capitol of that state and state bird. This is done by reading in a text file containing the information of all 50 states. This is the code that I am currently working with. This is a small part of a menu that I am working on.

 elif x == "2":
    f = open("States and Capitals.txt", "r")
    x = input("Enter the state you would like to search: ") 
    searchlines = f.read()
    for x, line in enumerate(searchlines):
        if x in line:
            for l in searchlines[i:i+3]: print l,
        print(x)
    f.close()

Example of Text file:

Alabama

Capital: Montgomery

State Bird: Yellowhammer

State Flower: Camellia

Alaska

Capital: Juneau

State Bird: Willow Ptarmigan

State Flower: Forget Me Not

Arizona

Capital: Phoenix

State Bird: Cactus Wren

State Flower: Saguaro Cactus Blossom

Upvotes: 2

Views: 1116

Answers (4)

martineau
martineau

Reputation: 123531

Here's a way to read the file three lines at time and prints the data from the state it finds that matches (if any):

from itertools import zip_longest

# See https://docs.python.org/3/library/itertools.html#itertools-recipes
def grouper(iterable, n, fillvalue=None):
    ''' Collect data into fixed-length chunks or blocks. '''
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)


target_state = input('Please enter a state name: ')

with open('States and Capitals.txt', 'r') as file:
    for group in grouper(file, 3, ''):  # Read file three lines at a time.
        state, capital, bird = map(str.rstrip, group)  # Remove newlines.
        if state == target_state:
            print(f'State: {state}, Bird: {bird}')
            break  # All done.
    else:
        print(f'Error: No state found named {target_state}')

Sample output:

State: Kansas, Bird: Western Meadowlark

Upvotes: 0

h0r53
h0r53

Reputation: 3229

Try this. You can first split your file input into a list with the split() function, which in this case is using "\n" or newline as a delimiter. Then you just print the next 3 lines from the index or your found string (if it exists). Here I am assuming you want to print the state, the capital, the bird, and the flower (4 lines total).

elif x == "2":
    f = open("States and Capitals.txt", "r")
    x = input("Enter the state you would like to search: ") 
    searchlines = f.read().split("\n")
    if x in searchlines:
        index = searchlines.index(x)
        for i in range(4):
            print(searchlines[index+i])
    f.close()

If you want to exclude the State from the output because it is possibly redundant, then you can make the following minor alteration:

elif x == "2":
    f = open("States and Capitals.txt", "r")
    x = input("Enter the state you would like to search: ") 
    searchlines = f.read().split("\n")
    if x in searchlines:
        index = searchlines.index(x)
        for i in range(1,4):
            print(searchlines[index+i])
    f.close()

Upvotes: 0

bart cubrich
bart cubrich

Reputation: 1254

I think something like this may work. The result of this is you will get the variable output that has the line in it you want. You can then print that.

elif x == "2":
    state= input("\nPlease enter a State.\n")
    with open("States and Capitals.txt", "r") as f:
        for line in f:
            if state.lower() in line.lower(): output=line

Upvotes: 0

ArunJose
ArunJose

Reputation: 2174

You can use this code

f = open("States and Capitals.txt", "r")
x = input("enter value to search : ") 
searchlines = f.read()
if(searchlines.find(x)):
    print(x)
f.close()

Upvotes: 1

Related Questions