user3296651
user3296651

Reputation: 65

find specific word and read after that word in python

so i am very very new to python. need some basic help.

my logic is to find words in text file.

party A %aapple 1
Party B %bat 2
Party C c 3

i need to find all the words starts from %.

my code is

 searchfile = open("text.txt", "r")
for line in searchfile:
 for char in line:
if "%" in char:
    print char      

searchfile.close()

but the output is only the % character. I need the putput to be %apple and %bat

any help?

Upvotes: 1

Views: 619

Answers (2)

gregory
gregory

Reputation: 13023

For the sake of exemplification, I'm following up on Bipul Jain's reccomendation of showing how this can be done with regex:

import re

with open('text.txt', 'r') as f:
    file = f.read()

re.findall(r'%\w+', file)

results:

['%apple', '%bat']

Upvotes: 0

Bipul Jain
Bipul Jain

Reputation: 4643

You are not reading the file properly.

searchfile = open("text.txt", "r")

lines = [line.strip() for line in searchfile.readlines()]
for line in lines:
    for word in line.split(" "):
        if word.startswith("%"):
            print word

searchfile.close()

You should also explore regex to solve this as well.

Upvotes: 0

Related Questions